package com.efounder.pansoft.chat.photo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.core.view.ViewCompat;
import androidx.viewpager.widget.ViewPager;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.efounder.chat.R;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.view.HackyViewPager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.imageselector.photoview.PhotoView;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.FileUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * 仿QQ照片选择，viewpager查看
 * Created by will on 18-4-11.
 */

public class JFBigPicturePickActivity extends BaseActivity implements View.OnClickListener{

    private TextView tvRawPic, tvSend, tvNumber, tvNumberOf;
    private CheckBox cbRawPic;
    private ArrayList<String> urls = new ArrayList<>();
    ViewPager mViewPager;
    private int firstPosition = 0;
    private LinkedList<String> mPictureList = new LinkedList<>();
    private SamplePagerAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_big_picture_pick);
        // 延迟共享动画的执行
        ActivityCompat.postponeEnterTransition(this);

        ArrayList<String> tempList = (ArrayList<String>) getIntent().getExtras().get("mPictureList");
        firstPosition = getIntent().getIntExtra("curIndex", 0);
        mPictureList.addAll(tempList);

        tvRawPic = (TextView) findViewById(R.id.tv_raw_pic);
        tvSend = (TextView) findViewById(R.id.tv_send_pic);
        cbRawPic = (CheckBox) findViewById(R.id.cb_raw_pic);
        tvNumber = (TextView) findViewById(R.id.tv_number);
        tvNumberOf = (TextView) findViewById(R.id.tv_numberOf);
        tvNumber.setOnClickListener(this);
        tvRawPic.setOnClickListener(this);
        tvSend.setOnClickListener(this);
        cbRawPic.setOnClickListener(this);

        cbRawPic.setChecked(EnvironmentVariable.getProperty("picture_pick_is_raw_pic","false").equals("true"));
        if (cbRawPic.isChecked()) {
            setupRawPic();
        }
        mViewPager = (HackyViewPager) findViewById(R.id.view_pager);

        mViewPager.setPageMargin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, this.getResources().getDisplayMetrics()));

        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                ArrayList<SelectModel> tempSelectModelList = JFMessagePicturePickView.getAllPicture(JFBigPicturePickActivity.this, -1);
                for (SelectModel selectModel : tempSelectModelList) {
                    urls.add(selectModel.getPath());
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new SamplePagerAdapter(JFBigPicturePickActivity.this, urls);
                        mViewPager.setAdapter(adapter);
                        mViewPager.setCurrentItem(firstPosition);
                        tvNumberOf.setText(firstPosition+1+"/"+urls.size());
                        int index = mPictureList.indexOf(urls.get(firstPosition));
                        if (index == -1){
                            tvNumber.setText("");
                            tvNumber.setBackground(getResources().getDrawable(R.drawable.jf_circle_no_number_bg));
                        }else {
                            tvNumber.setText(index+1+"");
                            tvNumber.setBackground(getResources().getDrawable(R.drawable.qq_style_circle_number_bg));
                        }
                    }
                });
            }
        });

        setupButton();

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tvNumberOf.setText(position+1+"/"+urls.size());
                int index = mPictureList.indexOf(urls.get(position));
                if (index == -1){
                    tvNumber.setText("");
                    tvNumber.setBackground(getResources().getDrawable(R.drawable.jf_circle_no_number_bg));
                }else {
                    tvNumber.setText(index+1+"");
                    tvNumber.setBackground(getResources().getDrawable(R.drawable.qq_style_circle_number_bg));
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        cbRawPic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setupRawPic();
            }
        });

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_number) {
            int curPosition = mViewPager.getCurrentItem();
            setupNumIndicator(curPosition);
            setupRawPic();
            setupButton();

        } else if (id == R.id.tv_raw_pic) {
            cbRawPic.setChecked(!cbRawPic.isChecked());
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", String.valueOf(cbRawPic.isChecked()));
        } else if (id == R.id.tv_send_pic) {
            if (mPictureList.size() == 0) {
                mPictureList.add(urls.get(mViewPager.getCurrentItem()));
            }
            Intent intent = new Intent();
            intent.putExtra("mSelectedPics", mPictureList);
            intent.putExtra("isRawPic", cbRawPic.isChecked());
            setResult(RESULT_OK, intent);
            finish();
            EnvironmentVariable.setProperty("picture_pick_is_raw_pic", "false");
            mPictureList.clear();
        }
    }

    public class SamplePagerAdapter extends PagerAdapter {

        private Context context;
        private ArrayList<String> urls;

        public SamplePagerAdapter(Context context, ArrayList<String> urls) {
            this.context = context;
            this.urls = urls;
        }

        @Override
        public int getCount() {
            return urls.size();
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            PhotoView photoView = new PhotoView(container.getContext());
            if (position == firstPosition) {
                ViewCompat.setTransitionName(photoView, "imageItem");
                scheduleStartPostponedTransition(photoView);
            }

            LXGlideImageLoader.getInstance().displayImage(context,photoView,urls.get(position),R.drawable.loading_image_background);
            // Now just add PhotoView to ViewPager and return it
            container.addView(photoView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            return photoView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    //共享元素动画延时执行
    private void scheduleStartPostponedTransition(final View sharedElement) {
        sharedElement.getViewTreeObserver().addOnPreDrawListener(
                new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        //启动动画
                        sharedElement.getViewTreeObserver().removeOnPreDrawListener(this);
                        ActivityCompat.startPostponedEnterTransition(JFBigPicturePickActivity.this);
                        return true;
                    }
                });
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        EventBus.getDefault().post(new PicturePickEvent(mPictureList, cbRawPic.isChecked()));
        ActivityCompat.finishAfterTransition(this);
        //finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Glide.get(this).clearMemory();
    }

    /**
     *设置选择序号
     */
    private void setupNumIndicator(int position) {
        int index = mPictureList.indexOf(urls.get(position));
        if (index == -1){//不存在则加入数组里
            mPictureList.add(urls.get(position));
            tvNumber.setText(mPictureList.size()+"");
            tvNumber.setBackground(getResources().getDrawable(R.drawable.qq_style_circle_number_bg));
        }else {
            mPictureList.remove(index);
            tvNumber.setText("");
            tvNumber.setBackground(getResources().getDrawable(R.drawable.jf_circle_no_number_bg));
        }
    }

    /**
     * 设置原图按钮
     */
    private void setupRawPic() {
        tvRawPic.setTextColor(getResources().getColor(R.color.chat_red));
        if (cbRawPic.isChecked()) {
            if (mPictureList.size() > 0) {
                String size = FileUtils.getFilesSize(mPictureList);
                tvRawPic.setText(ResStringUtil.getString(R.string.common_text_raw_pic) + "(" + size + ")");
            }else {
                tvRawPic.setText(R.string.common_text_raw_pic);
            }
        } else {
            tvRawPic.setTextColor(getResources().getColor(R.color.white));
            tvRawPic.setText(R.string.common_text_raw_pic);
        }
    }
    /**
     * 设置确定按钮
     */
    private void setupButton() {
        if (mPictureList.size() > 0) {
            tvSend.setText(ResStringUtil.getString(R.string.common_text_confirm)+"(" + mPictureList.size() + ")");
        } else {
            tvSend.setText(R.string.common_text_confirm);
        }
    }
}
