package de.beyondsoft.ownchat.filepicker.adapters;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;


import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.util.ArrayList;

import de.beyondsoft.ownchat.R;
import de.beyondsoft.ownchat.filepicker.FilePickerConst;
import de.beyondsoft.ownchat.filepicker.PickerManager;
import de.beyondsoft.ownchat.filepicker.models.Media;
import de.beyondsoft.ownchat.filepicker.utils.AndroidLifecycleUtils;
import de.beyondsoft.ownchat.utils.ui.GlideApp;

public class ImageGridAdapter extends SelectableAdapter<ImageGridAdapter.ImageViewHolder, Media> {
    private final Context context;
    private final boolean showCamera;
    private final FileAdapterListener mListener;
    private int imageSize;

    private final static int ITEM_TYPE_CAMERA = 100;
    private final static int ITEM_TYPE_PHOTO  = 101;
    private View.OnClickListener cameraOnClickListener;

    public ImageGridAdapter(Context context, ArrayList<Media> medias, ArrayList<String> selectedPaths, boolean showCamera, FileAdapterListener photoGridAdapterListener) {
        super(medias, selectedPaths);
        this.context = context;
        this.showCamera = showCamera;
        this.mListener = photoGridAdapterListener;
        setColumnNumber(context,4);
    }

    @Override
    public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.item_image_layout, parent, false);

        return new ImageViewHolder(itemView);
    }

    @Override
    public int getItemViewType(int position) {
        if(showCamera) {
            return (position == 0) ? ITEM_TYPE_CAMERA : ITEM_TYPE_PHOTO;
        } else {
            return ITEM_TYPE_PHOTO;
        }
    }

    @Override
    public void onBindViewHolder(final ImageViewHolder holder, int position) {
        if(getItemViewType(position) == ITEM_TYPE_PHOTO) {
            final Media media = getItems().get(showCamera ? position - 1 : position);

            if(AndroidLifecycleUtils.canLoadImage(holder.imageView.getContext())) {
                GlideApp.with(holder.imageView.getContext())
                        .asBitmap()
                        .load(new File(media.getPath()))
                        .override(imageSize, imageSize)
                        .thumbnail(.25f)
                        .into(holder.imageView);
            }


            if(media.getMediaType()== FilePickerConst.MEDIA_TYPE_VIDEO) {
                holder.videoIcon.setVisibility(View.VISIBLE);
            } else {
                holder.videoIcon.setVisibility(View.GONE);
            }

            holder.itemView.setOnClickListener(v -> onItemClicked(holder,media));

            //in some cases, it will prevent unwanted situations
            holder.checkBox.setVisibility(View.GONE);
            holder.checkBox.setOnCheckedChangeListener(null);
            holder.checkBox.setOnClickListener(view -> onItemClicked(holder,media));

            //if true, your checkbox will be selected, else unselected
            holder.checkBox.setChecked(isSelected(media));

            holder.selectBg.setVisibility(isSelected(media) ? View.VISIBLE : View.GONE);
            holder.checkBox.setVisibility(isSelected(media) ? View.VISIBLE : View.GONE);

            holder.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                toggleSelection(media);
                holder.selectBg.setVisibility(isChecked ? View.VISIBLE : View.GONE);

                if (isChecked) {
                    holder.checkBox.setVisibility(View.VISIBLE);
                    PickerManager.getInstance().add(media.getPath(), FilePickerConst.FILE_TYPE_MEDIA);
                } else {
                    holder.checkBox.setVisibility(View.GONE);
                    PickerManager.getInstance().remove(media.getPath(),FilePickerConst.FILE_TYPE_MEDIA);
                }

                if(mListener != null) {
                    mListener.onItemSelected();
                }
            });
        } else {
            holder.imageView.setImageResource(PickerManager.getInstance().getCameraDrawable());
            holder.checkBox.setVisibility(View.GONE);
            holder.itemView.setOnClickListener(cameraOnClickListener);
            holder.videoIcon.setVisibility(View.GONE);
        }
    }

    private void onItemClicked(ImageViewHolder holder, Media media) {
        if(PickerManager.getInstance().getMaxCount() == 1) {
            PickerManager.getInstance().add(media.getPath(), FilePickerConst.FILE_TYPE_MEDIA);

            if(mListener!=null) {
                mListener.onItemSelected();
            }
        } else if (holder.checkBox.isChecked() || PickerManager.getInstance().shouldAdd()) {
            holder.checkBox.setChecked(!holder.checkBox.isChecked());
        }
    }

    private void setColumnNumber(Context context, int columnNum) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        int widthPixels = metrics.widthPixels;
        imageSize = widthPixels / columnNum;
    }

    @Override
    public int getItemCount() {
        if(showCamera) {
            return getItems().size() + 1;
        }

        return getItems().size();
    }

    public void setCameraListener(View.OnClickListener onClickListener) {
        this.cameraOnClickListener = onClickListener;
    }

    static class ImageViewHolder extends RecyclerView.ViewHolder {
        CheckBox checkBox;

        ImageView imageView;

        ImageView videoIcon;

        View selectBg;

        ImageViewHolder(View itemView) {
            super(itemView);
            checkBox = itemView.findViewById(R.id.checkbox);
            imageView = itemView.findViewById(R.id.iv_photo);
            videoIcon = itemView.findViewById(R.id.video_icon);
            selectBg = itemView.findViewById(R.id.transparent_bg);
        }
    }
}
