/*******************************************************************************
 * Copyright 2011, 2012 Chris Banes.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.efounder.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
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.Button;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.efounder.chat.R;
import com.efounder.chat.utils.IdentifyQrCodeManager;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.view.HackyViewPager;
import com.efounder.chat.zxing.qrcode.QRManager;
import com.efounder.imageloader.GlideImageLoader;
import com.efounder.imageselector.photoview.PhotoView;
import com.efounder.imageselector.photoview.PhotoViewAttacher;
import com.efounder.util.AppContext;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.ImageUtils;
import com.utilcode.util.ScreenUtils;
import com.utilcode.util.StatusBarUtil;

import java.io.File;
import java.util.List;


public class ViewPagerActivity extends BaseActivity {

    private String[] urls;
    private int firstPosition = 0;
    private IdentifyQrCodeManager identifyQrCodeManager = new IdentifyQrCodeManager();
    private Button btnSacnQrcode;


    /**
     * 跳转显示图片墙
     *
     * @param urls     要显示的图片数组
     * @param position 要显示的位置
     * @param view     元素动画view 可以为null
     */
    public static void showImageWall(Context mContext, String[] urls, int position, View view) {
        Intent intent = new Intent(mContext, ViewPagerActivity.class);
        intent.putExtra("urls", urls);
        intent.putExtra("position", position);
        if (view != null) {
            //使用元素动画跳转
            ActivityOptionsCompat options = ActivityOptionsCompat
                    .makeSceneTransitionAnimation((Activity) mContext, view, "imageItem");
            ActivityCompat.startActivity(mContext, intent, options.toBundle());
        } else {
            mContext.startActivity(intent);
        }
    }

    public static void showImageWall(Context mContext, List<String> urlList, int position, View view) {
        if (urlList == null || urlList.size() == 0) {
            return;
        }
        String[] urls = new String[urlList.size()];
        showImageWall(mContext, urls, position, view);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_view_pager);
        setSwipeBackEnable(false);
        // 延迟共享动画的执行
        ActivityCompat.postponeEnterTransition(this);

        Button btnSave = (Button) findViewById(R.id.btn_save);
        btnSacnQrcode = (Button) findViewById(R.id.btn_sacn_qrcode);
        final ViewPager mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
        urls = getIntent().getStringArrayExtra("urls");
        firstPosition = getIntent().getIntExtra("position", 0);
        mViewPager.setAdapter(new SamplePagerAdapter(this, urls));

        mViewPager.setPageMargin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, this.getResources().getDisplayMetrics()));
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                btnSacnQrcode.setVisibility(View.GONE);
                if (urls[position].startsWith("http")) {
                    Glide.with(ViewPagerActivity.this)
                            .asFile()
                            .apply(new RequestOptions().dontAnimate())
                            .load(urls[position])
                            .into(new SimpleTarget<File>() {
                                @Override
                                public void onResourceReady(@NonNull File file,
                                                            Transition<? super File> transition) {
                                    scanQrcode(file.getAbsolutePath());
                                }
                            });

                } else {
                    String path = urls[position].replace("file://", "");

                    scanQrcode(path);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.setCurrentItem(firstPosition);
        final Handler mHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        Toast.makeText(AppContext.getCurrentActivity(), ResStringUtil.getString(R.string.chat_photo_save_to) +
                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + ResStringUtil.getString(R.string.chat_under_catalog), Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(AppContext.getCurrentActivity(), ResStringUtil.getString(R.string.chat_photo_save_fail), Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(AppContext.getCurrentActivity(), ResStringUtil.getString(R.string.chat_photo_existed), Toast.LENGTH_SHORT).show();
                    default:
                        break;
                }
            }
        };
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String uri = urls[mViewPager.getCurrentItem()];
                ImageUtil.saveNetWorkImage(uri, mHandler);
            }
        });

    }

    @Override
    protected void setStatusBarColor() {
        //设置状态栏全透明，图片显示到状态栏
        StatusBarUtil.setTransparent(this);
    }

    public void scanQrcode(final String filePath1) {
        //识别图片二维码
        identifyQrCodeManager.scanImage(filePath1, new IdentifyQrCodeManager.ScanCallBack() {
            @Override
            public void scanSuccess(String filePath, final String reult) {
                if (filePath1.equals(filePath)) {
                    btnSacnQrcode.setVisibility(View.VISIBLE);
                    btnSacnQrcode.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            QRManager.handleresult(ViewPagerActivity.this, (String) reult, false);
                        }
                    });
                }
            }

            @Override
            public void scanFail() {
                btnSacnQrcode.setVisibility(View.GONE);
            }
        });
    }

    public class SamplePagerAdapter extends PagerAdapter {

        private Context context;
        private String[] urls;

        public SamplePagerAdapter(Context context, String[] urls) {
            this.context = context;
            this.urls = urls;
        }

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

        @Override
        public View instantiateItem(final ViewGroup container, final int position) {

            View view = View.inflate(context, R.layout.wechatview_pager_item_pic, null);
            final PhotoView ivPagerPic = view.findViewById(R.id.iv_pager_item_pic);
            final SubsamplingScaleImageView imageView = view.findViewById(R.id.imageView);

            if (position == firstPosition) {
                ViewCompat.setTransitionName(view, "imageItem");
                scheduleStartPostponedTransition(view);
            }

            ivPagerPic.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    onBackPressed();
                }

                @Override
                public void onOutsidePhotoTap() {
                    onBackPressed();
                }
            });

//            //todo 如果是网络图片
            if (urls[position].startsWith("http")) {
                Glide.with(ViewPagerActivity.this)
                        .asFile()
                        .apply(new RequestOptions().dontAnimate())
                        .load(urls[position])
                        .into(new SimpleTarget<File>() {
                            @Override
                            public void onResourceReady(@NonNull File file,
                                                        Transition<? super File> transition) {
                                showFileImage(file, imageView, ivPagerPic);
                            }
                        });

            } else {
                String path = urls[position].replace("file://", "");
                showFileImage(new File(path), imageView, ivPagerPic);

            }


//            Glide.with(context.getApplicationContext())
//                    .asBitmap()
//                    .apply(new RequestOptions().dontAnimate())
//                    .load(urls[position])
//                    .into(new SimpleTarget<Bitmap>() {
//                        @Override
//                        public void onResourceReady(@NonNull Bitmap bitmap,
//                                                    Transition<? super Bitmap> transition) {
//
//                            int w = bitmap.getWidth();
//                            int h = bitmap.getHeight();
//                            if (h > ScreenUtils.getScreenHeight() * 2) {
//                                //处理长图
//                                ivPagerPic.setScaleType(ImageView.ScaleType.CENTER_CROP);
//                                float scale = 1 / (float) (h / ScreenUtils.getScreenHeight() * 4);
//                                ivPagerPic.setMinimumScale(scale);
//                                ivPagerPic.setMediumScale(0.5f);
//                                ivPagerPic.setMaximumScale(1);
//                                int maxHeitht = 8192;
//                                maxHeitht = AndroidOpenGLUtil.getMaxSupportSize();
//                                if (maxHeitht == 0 || maxHeitht < 8192) {
//                                    maxHeitht = 8192;
//                                }
//
//                                if (w > maxHeitht || h > maxHeitht) {
//                                    int subSampleScale = Math.max(w, h) / maxHeitht;
//                                    Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap,
//                                            w / (subSampleScale * 2),
//                                            h / (subSampleScale * 2), true);
//                                    ivPagerPic.setImageBitmap(bitmap1);
//                                    //bitmap.recycle();
//                                    return;
//                                }
//                            } else {
//                                if (context == null) {
//                                    return;
//                                }
//                                GlideImageLoader.getInstance().displayImage(context, ivPagerPic, urls[position], R.drawable.loading_image_background);
//                            }
//
//                        }
//                    });

            container.addView(view);
            return view;
        }

        @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;
        }

    }

    /**
     * 加载图片
     *
     * @param file
     * @param scaleImageView 加载图片使用
     * @param ivPagerPic     加载gif 使用
     */
    private void showFileImage(final File file, SubsamplingScaleImageView scaleImageView, PhotoView ivPagerPic) {
        if (!file.exists()) {
            return;
        }
        if (ImageUtil.isGifFile(file)) {
            GlideImageLoader.getInstance().displayImage(this, ivPagerPic, file, R.drawable.loading_image_background);
            return;
        }
        scaleImageView.setVisibility(View.VISIBLE);
        ivPagerPic.setVisibility(View.GONE);

        //获取图片宽高，如果是长图，使用centercrop
        String scale1 = ImageUtil.getPicScale(file.getAbsolutePath());
        String[] size = scale1.split(":");
        int h = Integer.valueOf(size[1]);
        if (h > ScreenUtils.getScreenHeight() * 2) {
//            scaleImageView.setMinScale(0.5f);
//            scaleImageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_START);
        }

        scaleImageView.setMaxScale(5F);
//        scaleImageView.setMinScale(0.5F);
        scaleImageView.setDoubleTapZoomScale(0.8f);
        //获取图片方向
        int oratation = ImageUtils.getBitmapDegree(file.getAbsolutePath());
        //设置图片方向
        scaleImageView.setOrientation(oratation);
        //设置图片
        scaleImageView.setImage(ImageSource.uri(file.getAbsolutePath()));
        //这个待验证
        // scaleImageView.setImage(ImageSource.uri(file.getAbsolutePath()), new ImageViewState(1.0F, new PointF(0, 0), oratation));

//        String scale1 = ImageUtil.getPicScale(file.getAbsolutePath());
//        String[] size = scale1.split(":");
//        int w = Integer.valueOf(size[0]);
//        int h = Integer.valueOf(size[1]);
//
//        if (h > ScreenUtils.getScreenHeight() * 2) {
//            //处理长图
//            ivPagerPic.setScaleType(ImageView.ScaleType.CENTER_CROP);
//            float scale = 1 / (float) (h / ScreenUtils.getScreenHeight() * 4);
//            ivPagerPic.setMinimumScale(scale);
//            ivPagerPic.setMediumScale(0.5f);
//            ivPagerPic.setMaximumScale(1);
//            int maxHeitht = AndroidOpenGLUtil.getMaxSupportSize();
//            if (maxHeitht == 0 || maxHeitht < 8192) {
//                maxHeitht = 8192;
//            }
//
//            if (w > maxHeitht || h > maxHeitht) {
//                int subSampleScale = Math.max(w, h) / maxHeitht;
//
//                BitmapFactory.Options options = new BitmapFactory.Options();
//                options.inPreferredConfig = RGB_565;
//                Bitmap orBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
//
//                Bitmap bitmap1 = Bitmap.createScaledBitmap(orBitmap,
//                        w / (subSampleScale * 2),
//                        h / (subSampleScale * 2), true);
//                ivPagerPic.setImageBitmap(bitmap1);
//                orBitmap.recycle();
//                return;
//            }
//        } else {
//            GlideImageLoader.getInstance().displayImage(ivPagerPic.getContext(), ivPagerPic, file, R.drawable.loading_image_background);
//        }

    }

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


//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                            getWindow().setExitTransition(new android.transition.Fade());
//                            getWindow().setEnterTransition(new android.transition.Fade());
//                            /**
//                             * 3、设置ShareElementTransition,指定的ShareElement会执行这个Transiton动画
//                             */
//                            TransitionSet transitionSet = new TransitionSet();
//                            transitionSet.addTransition(new ChangeBounds());
//                            transitionSet.addTransition(new ChangeTransform());
//                            transitionSet.addTarget(sharedElement);
//                            getWindow().setSharedElementEnterTransition(transitionSet);
//                            getWindow().setSharedElementExitTransition(transitionSet);
//                        }

                        ActivityCompat.startPostponedEnterTransition(ViewPagerActivity.this);

                        return true;
                    }
                });
    }


    @Override
    public void onBackPressed() {
        ActivityCompat.finishAfterTransition(this);
        //finish();
    }

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