package com.ads.cal.picturetranslate.activity;

import static com.ads.cal.picturetranslate.SharedPreferencesUtil.KEY_FIRST_INSTALL_APP;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.ExperimentalGetImage;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.ads.cal.picturetranslate.PictureTranslateUtils;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.SharedPreferencesUtil;
import com.ads.cal.picturetranslate.base.BaseActivity;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

@ExperimentalGetImage
public class PictureTranslateStartActivity extends BaseActivity {

    private MyHandler handler;
    private ProgressBar bar;
    private ViewPager viewPager;
    private final int[] images = {R.mipmap.image1, R.mipmap.image2, R.mipmap.image3}; // 图片资源
    private int currentPage = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        initView();
    }

    private void initView() {
        GifImageView imageView = findViewById(R.id.gifimg);
        try {
            GifDrawable gifFromAssets = new GifDrawable(getAssets(), "app_gif.gif");
            gifFromAssets.setLoopCount(1);
            imageView.setImageDrawable(gifFromAssets);
        } catch (IOException e) {
            e.printStackTrace();
        }

        bar = findViewById(R.id.horizontalProgressBar);
        handler = new MyHandler(this);
        TextView try_it_now = findViewById(R.id.try_it_now);
        String firstInstall = SharedPreferencesUtil.getString(this, KEY_FIRST_INSTALL_APP, "");
        if (!TextUtils.isEmpty(firstInstall)) {
            try_it_now.setVisibility(View.GONE);
            bar.setVisibility(View.VISIBLE);
            handler.sendEmptyMessage(1);
        } else {
            try_it_now.setOnClickListener(v -> {
                PictureTranslateListMainActivity.PictureTranslateListMainActivityStart(PictureTranslateStartActivity.this);
                SharedPreferencesUtil.saveString(PictureTranslateStartActivity.this, KEY_FIRST_INSTALL_APP, "install");
                finish();
            });

            playBanner();
        }
    }

    public void setProgressBarProgress(int i) {
        if (i > 100) {
            if (handler != null) {
                handler.removeCallbacksAndMessages(null);
            }
            PictureTranslateListMainActivity.PictureTranslateListMainActivityStart(this);
            finish();
            return;
        }
        bar.setProgress(i);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }

    private static class MyHandler extends Handler {

        private final WeakReference<Activity> weakReference;
        private int i = 0;

        public MyHandler(Activity activity) {
            super();
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Activity activity = weakReference.get();
            switch (msg.what) {
                case 1:
                    sendEmptyMessageDelayed(1, 10);
                    if (activity instanceof PictureTranslateStartActivity) {
                        ((PictureTranslateStartActivity) activity).setProgressBarProgress(i++);
                    }
                    break;
                case 2:
                    if (activity instanceof PictureTranslateStartActivity) {
                        ((PictureTranslateStartActivity) activity).smoothScroll();
                    }
                    sendEmptyMessageDelayed(2, 1500);
                    break;
            }
        }

    }

    public void smoothScroll() {
        if (currentPage == images.length) {
            currentPage = 0;
        }
        viewPager.setCurrentItem(currentPage++, currentPage != 0);

    }

    private ImageView im1, im2, im3;

    private void playBanner() {
        LinearLayout layout = findViewById(R.id.layout);
        im1 = findViewById(R.id.im_1);
        im2 = findViewById(R.id.im_2);
        im3 = findViewById(R.id.im_3);
        layout.setVisibility(View.VISIBLE);

        viewPager = findViewById(R.id.viewPager);
        ImagePagerAdapter adapter = new ImagePagerAdapter();
        viewPager.setAdapter(adapter);
        viewPager.setVisibility(View.VISIBLE);

        handler.sendEmptyMessageDelayed(2, 1500);
        viewPager.setOnTouchListener((v, event) -> {
            int action = event.getAction();
            if (action == MotionEvent.ACTION_DOWN) {
                handler.removeCallbacksAndMessages(null);
            } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
                handler.sendEmptyMessageDelayed(2, 1500);
            }
            return false;
        });
        // 手动滑动时停止自动滑动
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                currentPage = position;
                setImBg(currentPage);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void setImBg(int position) {
        switch (position) {
            case 0:
                im1.setBackgroundResource(R.drawable.app_f1a68f);
                im2.setBackgroundResource(R.drawable.app_ede0dc);
                im3.setBackgroundResource(R.drawable.app_ede0dc);
                break;
            case 1:
                im2.setBackgroundResource(R.drawable.app_f1a68f);
                im1.setBackgroundResource(R.drawable.app_ede0dc);
                im3.setBackgroundResource(R.drawable.app_ede0dc);
                break;
            case 2:
                im3.setBackgroundResource(R.drawable.app_f1a68f);
                im1.setBackgroundResource(R.drawable.app_ede0dc);
                im2.setBackgroundResource(R.drawable.app_ede0dc);
                break;
        }
    }

    private class ImagePagerAdapter extends PagerAdapter {

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

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

        @NonNull
        @Override
        public Object instantiateItem(@NonNull View container, int position) {
            ViewPager viewPager = (ViewPager) container;
            View imageView = getLayoutInflater().inflate(R.layout.image_item, viewPager, false);
            // 设置图片资源
            imageView.setBackgroundResource(images[position]);
            viewPager.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(@NonNull View container, int position, @NonNull Object object) {
            ViewPager viewPager = (ViewPager) container;
            viewPager.removeView((View) object);
        }
    }
}
