package com.efounder.pansoft.chat.photo;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ImageUtils;

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

/**
 * 仿QQ选择图片，文件夹列表
 * Created by will on 18-4-12.
 */

public class JFPicturePickerPhotoAlbumActivity extends BaseActivity {

    private ArrayList<PhotoAlbumLVItem> list = new ArrayList<>();
    private JFPickPhotoAlbumAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qq_style_activity_picture_pick_photo_album);
        setSwipeBackEnable(false);

        TextView titleView = (TextView) findViewById(R.id.tv_title);
        titleView.setText(R.string.wechatview_select_photo);
        TextView tvCancel = (TextView) findViewById(R.id.tv_save);
        tvCancel.setVisibility(View.VISIBLE);
        tvCancel.setText(R.string.common_text_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
                Intent intent = new Intent();
                intent.putExtra("cancel", true);
                setResult(RESULT_CANCELED, intent);
                finish();
            }
        });
        ListView listView = (ListView) findViewById(R.id.select_img_listView);

        adapter = new JFPickPhotoAlbumAdapter(this, list);
        listView.setAdapter(adapter);

        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                final ArrayList<SelectModel> arrayList = JFMessagePicturePickView.getAllPicture(JFPicturePickerPhotoAlbumActivity.this, -1);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //“最近照片”
                        if (arrayList.size() > 0) {
                            list.add(new PhotoAlbumLVItem(ResStringUtil.getString(R.string.wrchatview_recent_photos),
                                    arrayList.size(), arrayList.get(0).getPath()));
                        } else {
                            list.add(new PhotoAlbumLVItem(ResStringUtil.getString(R.string.wrchatview_recent_photos),
                                    arrayList.size(), ""));
                        }
                        //相册
                        list.addAll(getImagePathsByContentProvider());
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(JFPicturePickerPhotoAlbumActivity.this, JFPicturePickPhotoWallActivity.class);
                intent.putExtra(JFPicturePickPhotoWallActivity.SELECT_MODE, JFPicturePickPhotoWallActivity.mode);
                //第一行为“最近照片”
                if (position == 0) {
                    intent.putExtra("code", 200);
                } else {
                    //其他相册
                    intent.putExtra("code", 100);
                    intent.putExtra("folderPath", list.get(position).getPathName());
                }
                startActivityForResult(intent, JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE);
               // overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //将数据返回传递给JFPicturePickPhotoWallActivity
        if (requestCode == JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE &&
                resultCode == RESULT_OK) {
            setResult(RESULT_OK, data);
            finish();
            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
        }else if (requestCode == JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE &&
                resultCode == RESULT_CANCELED&& data!=null) {

            setResult(RESULT_CANCELED, data);
            finish();

            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
        }
    }

    //重写返回键
    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
            Intent intent = new Intent();
            intent.putExtra("cancel", true);
            setResult(RESULT_CANCELED, intent);
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onBackPressed() {

        overridePendingTransition(R.anim.push_bottom_in, R.anim.push_bottom_out);
        Intent intent = new Intent();
        intent.putExtra("cancel", true);
        setResult(RESULT_CANCELED, intent);
        finish();
    }

    /**
     * 获取目录中图片的个数。
     */
    private int getImageCount(File folder) {
        int count = 0;
        File[] files = folder.listFiles();
        if (files ==null){
            return 0;
        }
        for (File file : files) {
            if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_PIC_ONLY) {
                //图片模式，所有图片数量
                if (ImageUtils.isImage(file)) count++;
            } else if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_PIC_VIDEO) {
                //混合模式，图片视频数量
                if (ImageUtils.isImage(file) || file.getName().endsWith(".mp4")
                        || file.getName().endsWith(".avi")
                        ||file.getName().endsWith(".3gp") || file.getName().endsWith(".mkv")) count++;
            }else {
                //视频模式，视频数量
                if (file.getName().endsWith(".mp4") || file.getName().endsWith(".avi")
                        ||file.getName().endsWith(".3gp") || file.getName().endsWith(".mkv")) count++;
            }

        }

        return count;
    }

    /**
     * 获取目录中最新的一张图片的绝对路径。
     */
    private String getFirstImagePath(File folder) {
        File[] files = folder.listFiles();
        if (files==null) {
            return null;
        }
        for (int i = files.length - 1; i >= 0; i--) {
            File file = files[i];
            if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_PIC_ONLY) {
                //图片模式，查第一张图片
                if (ImageUtils.isImage(file)) {
                    return file.getAbsolutePath();
                }
            } else if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_PIC_VIDEO) {
                //混合模式，查第一张图片或视频
                if (ImageUtils.isImage(file) || file.getName().endsWith(".mp4")
                        || file.getName().endsWith(".avi")
                        ||file.getName().endsWith(".3gp") || file.getName().endsWith(".mkv")){
                    return file.getAbsolutePath();
                }
            } else {
                //视频模式，查第一个视频
                if (file.getName().endsWith(".mp4")
                        || file.getName().endsWith(".avi")
                        ||file.getName().endsWith(".3gp") || file.getName().endsWith(".mkv")) {
                    return file.getAbsolutePath();
                }
            }

        }

        return null;
    }

    /**
     * 使用ContentProvider读取SD卡所有图片。
     */
    private ArrayList<PhotoAlbumLVItem> getImagePathsByContentProvider() {
        Cursor cursor;
        ContentResolver mContentResolver = getContentResolver();
        //图片模式
        if (JFPicturePickPhotoWallActivity.mode == JFPicturePickPhotoWallActivity.MODE_PIC_ONLY) {
            Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

            String key_MIME_TYPE = MediaStore.Images.Media.MIME_TYPE;
            String key_DATA = MediaStore.Images.Media.DATA;

            // 只查询jpg和png的图片
            cursor = mContentResolver.query(mImageUri, new String[]{key_DATA},
                    key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=?",
                    new String[]{"image/jpg", "image/jpeg", "image/png", "image/gif"},
                    MediaStore.Images.Media.DATE_MODIFIED);
        }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};
            String largeFileSort = MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC";
            String 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 = mContentResolver
                    .query(MediaStore.Files.getContentUri("external"),
                            largeFileProjection, selection, null, largeFileSort);
        } else {
            //视频模式
            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};
            String largeFileSort = MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC";
            String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "="
                    + MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
            cursor = mContentResolver
                    .query(MediaStore.Files.getContentUri("external"),
                            largeFileProjection, selection, null, largeFileSort);
        }
        ArrayList<PhotoAlbumLVItem> list = new ArrayList<>();
        if (cursor != null) {
            if (cursor.moveToLast()) {
                //路径缓存，防止多次扫描同一目录
                HashSet<String> cachePath = new HashSet<String>();
                list = new ArrayList<PhotoAlbumLVItem>();

                while (true) {
                    // 获取图片的路径
                    String imagePath = cursor.getString(cursor.getColumnIndexOrThrow( MediaStore.Files.FileColumns.DATA));

                    File parentFile = new File(imagePath).getParentFile();
                    String parentPath = parentFile.getAbsolutePath();

                    //不扫描重复路径
                    if (!cachePath.contains(parentPath)) {
                        list.add(new PhotoAlbumLVItem(parentPath, getImageCount(parentFile),
                                getFirstImagePath(parentFile)));
                        cachePath.add(parentPath);
                    }

                    if (!cursor.moveToPrevious()) {
                        break;
                    }
                }
            }

            cursor.close();
        }

        return list;
    }
}