package com.efounder.pansoft.chat.photo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.imageselector.photoview.gestures.GestureDetector;
import com.efounder.imageselector.photoview.gestures.OnGestureListener;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.FileUtils;
import com.utilcode.util.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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

/**
 * 照片选择组件
 * Created by will on 18-4-9.
 */

public class JFMessagePicturePickView extends LinearLayout implements GestureDetector, View.OnClickListener {

    public static final int REQUEST_PIC_SELECTE_CODE = 2897;
    private TextView tvAlbum, tvRawPic, tvSend;
    private RecyclerView recyclerView;
    private CheckBox cbRawPic;
    private Context context;
    private JFPicturePickViewAdapter picturePickViewAdapter;
    private LinkedList<String> mPictureList = new LinkedList<>();
    private ArrayList<SelectModel> rawPictureList = new ArrayList<>();
    private OnPicSendListener onPicSendListener;
    //使用fragment跳转界面
    private Fragment fragment;

    public JFMessagePicturePickView(Context context) {
        this(context, null);
    }

    public JFMessagePicturePickView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        EventBus.getDefault().register(this);
        LayoutInflater.from(context).inflate(R.layout.view_message_picture_pick, this);
        recyclerView = findViewById(R.id.recyclerView);
        tvAlbum = findViewById(R.id.tv_album);
        tvRawPic = findViewById(R.id.tv_raw_pic);
        tvSend = findViewById(R.id.tv_send_pic);
        cbRawPic = findViewById(R.id.cb_raw_pic);
        tvAlbum.setOnClickListener(this);
        tvRawPic.setOnClickListener(this);
        tvSend.setOnClickListener(this);
        tvSend.setClickable(false);
        cbRawPic.setOnClickListener(this);

        cbRawPic.setChecked(false);
        EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");

        cbRawPic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked && mPictureList.size() > 0) {
                    String size = FileUtils.getFilesSize(mPictureList);
                    tvRawPic.setText(ResStringUtil.getString(R.string.wrchatview_original_image) + "(" + size + ")");
                } else {
                    tvRawPic.setText(R.string.wrchatview_original_image);
                }
                EnvironmentVariable.setProperty("picture_pick_is_raw_pic", String.valueOf(cbRawPic.isChecked()));
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        JFPicturePickPhotoWallActivity.mode = JFPicturePickPhotoWallActivity.MODE_PIC_ONLY;
//        rawPictureList = getAllPicture(context, 100);
        picturePickViewAdapter = new JFPicturePickViewAdapter(context, rawPictureList);
        recyclerView.setAdapter(picturePickViewAdapter);
        picturePickViewAdapter.setOnPicSelectedChangedListener(new JFPicturePickViewAdapter.OnPicSelectedChangedListener() {
            @Override
            public void onPicSelectedChanged(LinkedList<String> selectedList, boolean isRawPic) {
                cbRawPic.setChecked(isRawPic);
                dealSelectedList(selectedList);
            }

            @Override
            public void onPicSelectedChanged(LinkedList<String> selectedList) {
                dealSelectedList(selectedList);
            }

        });

    }

    /**
     * 设置图片高度 宽度自动计算
     *
     * @param height
     */
    public void setImageHeight(int height) {
        if (picturePickViewAdapter != null) {
            picturePickViewAdapter.setImageHeight(height);
        }

    }

    /**
     * 设置fragment
     *
     * @param fragment
     */
    public void setFragment(Fragment fragment) {
        this.fragment = fragment;

    }

    /**
     * 刷新相册数据
     */
    public void refreshPickView() {
        if (rawPictureList != null) {
            rawPictureList.clear();
            rawPictureList.addAll(getAllPicture(context, 50));
            if (picturePickViewAdapter != null) {
                picturePickViewAdapter.notifyDataSetChanged();
            }
        }

    }

    private void dealSelectedList(LinkedList<String> selectedList) {
        mPictureList = selectedList;
        if (cbRawPic.isChecked()) {
            String size = FileUtils.getFilesSize(mPictureList);
            tvRawPic.setText(ResStringUtil.getString(R.string.wrchatview_original_image) + "(" + size + ")");
        }
        if (selectedList.size() > 0) {
            tvSend.setText(ResStringUtil.getString(R.string.wrchatview_send) + "(" + selectedList.size() + ")");
            tvSend.setBackground(getResources().getDrawable(R.drawable.qq_style_rect_button_shape));
            tvSend.setTextColor(getResources().getColor(R.color.white));
            tvSend.setClickable(true);

        } else {
            tvSend.setText(R.string.wrchatview_send);
            tvSend.setBackground(getResources().getDrawable(R.drawable.qq_style_rect_button_shape_gray));
            tvSend.setTextColor(getResources().getColor(R.color.lightgray));
            tvSend.setClickable(false);
            tvRawPic.setText(R.string.wrchatview_original_image);
        }
    }

    @Override
    public void onClick(View v) {

        int id = v.getId();
        if (id == R.id.tv_album) {
            Intent intent = new Intent(context, JFPicturePickPhotoWallActivity.class);
            intent.putExtra("mPictureList", mPictureList);
            intent.putExtra(JFPicturePickPhotoWallActivity.MAX_NUM, 20);//可选择的最大照片数
            intent.putExtra(JFPicturePickPhotoWallActivity.SHOW_RAW_PIC, true);
            //todo 选择图片和视频
            intent.putExtra(JFPicturePickPhotoWallActivity.SELECT_MODE, JFPicturePickPhotoWallActivity.MODE_PIC_VIDEO);

            if (fragment != null) {
                fragment.startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
            } else {
                ((Activity) context).startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
            }

            mPictureList.clear();
            picturePickViewAdapter.notifyDataSetChanged();
            ((Activity) context).overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
        } else if (id == R.id.tv_raw_pic) {
            cbRawPic.setChecked(!cbRawPic.isChecked());
        } else if (id == R.id.tv_send_pic) {
            if (onPicSendListener == null) {
                return;
            }
            onPicSendListener.onPicSend(mPictureList, cbRawPic.isChecked());
            mPictureList.clear();
            cbRawPic.setChecked(false);
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
            picturePickViewAdapter.notifyDataSetChanged();
            dealSelectedList(mPictureList);
        }
    }

    @Override
    public boolean isScaling() {
        return false;
    }

    @Override
    public boolean isDragging() {
        return false;
    }

    @Override
    public void setOnGestureListener(OnGestureListener listener) {

    }

    public static ArrayList<SelectModel> getAllPicture(Context context, int maxCount) {
        String largeFileSort = MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC";
        String selection;
        Cursor cursor;
        //图片模式
        if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_PIC_ONLY) {
            String[] largeFileProjection = {
                    MediaStore.Files.FileColumns.DATA,
                    MediaStore.Files.FileColumns.DISPLAY_NAME,
                    MediaStore.Files.FileColumns.DATE_MODIFIED,
                    MediaStore.Files.FileColumns.MEDIA_TYPE,
                    MediaStore.Files.FileColumns.SIZE,
                    MediaStore.Files.FileColumns._ID,
                    MediaStore.Files.FileColumns.PARENT};
            selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
                    + MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
            cursor = context.getContentResolver()
                    .query(MediaStore.Files.getContentUri("external"), largeFileProjection, selection, null, largeFileSort);
        } else if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_PIC_VIDEO) {
            //图片视频模式
            String[] largeFileProjection = {
                    MediaStore.Files.FileColumns.DATA,
                    MediaStore.Files.FileColumns.DISPLAY_NAME,
                    MediaStore.Files.FileColumns.DATE_MODIFIED,
                    MediaStore.Files.FileColumns.MEDIA_TYPE,
                    MediaStore.Files.FileColumns.SIZE,
                    MediaStore.Files.FileColumns._ID,
                    MediaStore.Files.FileColumns.PARENT,
                    MediaStore.Video.VideoColumns.DURATION
            };
            selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
                    + MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE
                    + " OR "
                    + MediaStore.Files.FileColumns.MEDIA_TYPE + "="
                    + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
            cursor = context.getContentResolver()
                    .query(MediaStore.Files.getContentUri("external"), largeFileProjection, selection, null, largeFileSort);
        } else {
            //视频模式
            String[] largeFileProjection = {
                    MediaStore.Video.VideoColumns.DURATION,
                    MediaStore.Video.VideoColumns.DATA,
                    MediaStore.Video.VideoColumns.DISPLAY_NAME,
                    MediaStore.Video.VideoColumns.DATE_MODIFIED,
                    MediaStore.Video.VideoColumns.SIZE,
                    MediaStore.Video.VideoColumns._ID,
            };
            cursor = context.getContentResolver()
                    .query(MediaStore.Video.Media.getContentUri("external"), largeFileProjection, null, null, largeFileSort);
        }

        ArrayList<SelectModel> mFiles = new ArrayList<>();
        if (cursor == null) return mFiles;
        while (cursor.moveToNext()) {

            //获取图片的保存位置的数据
            byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));
            //将图片的保存位置的数据转换成字符串形式的路径
            String filePath = new String(data, 0, data.length - 1);
            if (maxCount != -1 && mFiles.size() >= maxCount) {
                break;
            }
            SelectModel selectModel;
            //照片模式
            if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_PIC_ONLY) {
//                if (ImageUtils.isImage(filePath)) {
                if (cursor.getInt(cursor.getColumnIndex(MediaStore.Files.FileColumns.MEDIA_TYPE)) == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {
                    selectModel = new SelectModel(filePath, MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE);
                    mFiles.add(selectModel);
                }
            }
            //照片视频
            else if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_PIC_VIDEO) {
//                if (ImageUtils.isImage(filePath)) {
                if (cursor.getInt(cursor.getColumnIndex(MediaStore.Files.FileColumns.MEDIA_TYPE)) == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {
                    selectModel = new SelectModel(filePath, MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE);
                } else {
                    selectModel = new SelectModel(filePath, MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO);
//                    if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_VIDEO_ONLY) {
                    int index = cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION);
                    if (index != -1) {
                        String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION));
                        if (duration.equals("null")) {
//                            selectModel.setSize("0:00:00");
                            selectModel.setSize(getVideoDuration(filePath));
                        } else {
                            selectModel.setSize(TimeUtils.formatTime(Long.valueOf(duration)));
                        }
                    } else {
                        selectModel.setSize(getVideoDuration(filePath));
                    }
                }
                mFiles.add(selectModel);
            }
            //单独视频模式
            else {
                selectModel = new SelectModel(filePath, MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO);
                if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_VIDEO_ONLY) {
                    String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION));
                    if ("null".equals(duration)) {
                        selectModel.setSize("0:00:00");
                    } else {
                        selectModel.setSize(TimeUtils.formatTime(Long.valueOf(duration)));
                    }
                } else {
                    selectModel.setSize(getVideoDuration(filePath));
                }
                mFiles.add(selectModel);
            }
        }
        cursor.close();
        return mFiles;
    }

    public interface OnPicSendListener {
        void onPicSend(LinkedList<String> mSelectedPics, boolean isRawPic);
    }

    public void setOnPicSendListener(OnPicSendListener onPicSendListener) {
        this.onPicSendListener = onPicSendListener;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSolvePicturePick(PicturePickEvent picturePickEvent) {
        mPictureList.clear();
        mPictureList.addAll(picturePickEvent.getList());
        picturePickViewAdapter.notifyDataSetChanged();
        cbRawPic.setChecked(picturePickEvent.isRawPic);
        dealSelectedList(picturePickEvent.getList());
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        EventBus.getDefault().unregister(this);
    }

    public static String getVideoDuration(String path) {
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            File file = new File(path);
            mediaPlayer.setDataSource(file.getPath());
            mediaPlayer.prepare();
            return TimeUtils.formatTime((long) mediaPlayer.getDuration());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mediaPlayer.release();
        }
        return "";
    }
}
