package com.ads.cal.picturetranslate.activity;

import static com.ads.cal.picturetranslate.SharedPreferencesUtil.KEY_FIRST_CLK_TAKE_PHOTO;
import static com.google.android.gms.ads.AdFormat.INTERSTITIAL;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.ExperimentalGetImage;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ads.cal.picturetranslate.LogUtils;
import com.ads.cal.picturetranslate.MessageEvent;
import com.ads.cal.picturetranslate.PermissionUtil;
import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.SharedPreferencesUtil;
import com.ads.cal.picturetranslate.ThreadUtils;
import com.ads.cal.picturetranslate.TopOnItAdManager;
import com.ads.cal.picturetranslate.adapter.PictureTranslateListAdapter;
import com.ads.cal.picturetranslate.base.BaseActivity;
import com.ads.cal.picturetranslate.bean.PictureTranslateBean;
import com.ads.cal.picturetranslate.fragment.DeleteFragment;
import com.ads.cal.picturetranslate.fragment.SettingFragment;
import com.android.gem.core.Event;
import com.android.gem.core.Node;
import com.gem.media.InitA;
import com.gem.media.StatsStaticHelper;
import com.gem.media.ad.AdmobInterstitialManager;
import com.gem.media.ad.GoogleMobileAdsConsentManager;
import com.gem.media.splash.base.protocol.AdCallback;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.PkgUtils;
import com.or.ange.dot.utils.LLog;


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

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;



@ExperimentalGetImage
public class PictureTranslateListMainActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {

    private static final String TAG = "PictureTranslateListMainActivity";
    private static final int REQUEST_CODE_PERMISSIONS = 1;
    private static final int PICK_IMAGE_REQUEST = 2;

    static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;

    private PictureTranslateListAdapter adapter;
    private LinearLayout notData;
    private RecyclerView recyclerView;
    private SettingFragment settingFragment;
    private FrameLayout settingContent;
    private TextView title, hintAnimText;
    private AnimatorSet animatorSet;
    private ImageView setting, home, delete, selectImg;


    private static final String CV_PKG = "cv_pkg";
    private static final String NODE = "node";
    private static final String MESSENGER = "messenger";
    private static final String APP_ID = "appid";
    private static final String T = "_";
    private static final String INTERSTITIAL = "interstitial";
    private static final String a_er = "a_er";

    private Messenger messenger = null;

    private boolean isFinished = false;

    private Node node;

    private String cvPkg;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (init == 0) {
            try {
                Intent intent = getIntent();
                if (intent == null) {
                    finish();
                    return;
                }
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
                initAdCallBack();
                initSource(intent);

            } catch (Exception e) {
                StatsStaticHelper.onEvent(a_er, Log.getStackTraceString(e));
                finish();
            }
            return;
        }
        setContentView(R.layout.acitivty_picture_translate);
        initView();
        initData();
        requestData();
        EventBus.getDefault().register(this);

        TopOnItAdManager.loadItAd();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (init == 0) {
            try {
                statPageShow();
                showAd();
            } catch (Exception e) {
//                LLog.d(TAG, "onStart" + Log.getStackTraceString(e));
                StatsStaticHelper.onEvent(a_er, Log.getStackTraceString(e));
                finish();
            }
        }
    }



    private void showAd() {
        if (AdmobInterstitialManager.instance().isAdAvailable()) {
            AdmobInterstitialManager.instance().showAd(this, Constants.SCENARIO_CHAPIN_PROCESS);
            report(Constants.NODE_CACHE, INTERSTITIAL);
        } else {
            LLog.d(TAG, "showAd" + 7);
            finish();
        }
    }

    private void statPageShow() {
        Event event = new Event();
        event.type = Constants.NODE_PAGE_SHOW;
        event.reason = getPackageName();
        addNodeEvent(event);
    }

    private void report(String type, String reason) {
        Event event = new Event();
        event.type = type;
        event.reason = reason;
        addNodeEvent(event);
    }

    private InterstitialAdCallback interstitialAdCallback = null;
    
    private void initAdCallBack() {
        if (null == interstitialAdCallback) {
            interstitialAdCallback = new InterstitialAdCallback(this);
        }
        AdmobInterstitialManager.instance().setAdCallback(interstitialAdCallback);
    }

    private void initSource(Intent intent) {
        if (intent == null) {
            finish();
            return;
        }

        try {
            cvPkg = intent.getStringExtra(CV_PKG);
            InitA.getInstance().setCvPkg(cvPkg);

            messenger = intent.getParcelableExtra(MESSENGER);
            node = intent.getParcelableExtra(NODE);

            String adAppId_channelId = intent.getStringExtra(APP_ID);
            LLog.w(TAG, "initSource  adAppId_channelId " + adAppId_channelId);

            if (!TextUtils.isEmpty(adAppId_channelId)) {
                String channelId = null;

                if (adAppId_channelId.contains(T)) {
                    String[] parts = adAppId_channelId.split(T);
                    if (parts.length > 1) {
                        channelId = parts[1];
                    }
                }

                if (TextUtils.isEmpty(channelId)) {
                    channelId = InitA.DEFAULT_APP_ID;
                }

                InitA.getInstance().initMediaApp(channelId);
            } else {
                InitA.getInstance().initMediaApp(InitA.DEFAULT_APP_ID);
            }
        } catch (Throwable throwable) {
            LLog.d(TAG, throwable.getMessage());
            StatsStaticHelper.onEvent(a_er, Log.getStackTraceString(throwable));
            finish();
        }
    }

    private void sendAdShowMessage() {
        if (messenger != null) {
            try {
                Message message = Message.obtain();
                message.what = 405;
                Bundle bundle = new Bundle();
                bundle.putString("pkgName", getPackageName());
                message.setData(bundle);
                messenger.send(message);
            } catch (Throwable e) {
                LLog.e(TAG, "finish e: " + Log.getStackTraceString(e));
            }
        }
    }

    @Override
    public void finish() {
        if (isFinished) {
            super.finish();
            return;
        }
        isFinished = true;
        super.finish();
        try {
            if (messenger != null) {
                Message message = Message.obtain();
                message.what = 404;
                Bundle bundle = new Bundle();
                if (node != null) {
                    bundle.putParcelable("node", node);
                }
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Throwable throwable) {
            LLog.e(TAG, "finish e: " + Log.getStackTraceString(throwable));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private String VN = "vn";
    private String VC = "vc";
    private String appVersionName = null;
    private String appVersionCode = null;

    private void addNodeEvent(Event event) {
        if (node != null) {
            try {
                JSONObject reason = new JSONObject();
                reason.put(Constants.TARGET_PKG, cvPkg);
                reason.put(Constants.MEDIA_PKG, getPackageName());
                reason.put(Constants.REASON, event.reason);
                if (TextUtils.isEmpty(appVersionName)) {
                    appVersionName = PkgUtils.getAppVersionName(PictureApplication.getApplication(), getPackageName());
                }
                if (TextUtils.isEmpty(appVersionCode)) {
                    appVersionCode = PkgUtils.getAppVersionCode(PictureApplication.getApplication(), getPackageName());
                }
                reason.put(VN, appVersionName);
                reason.put(VC, appVersionCode);
                event.reason = reason.toString();
            } catch (Exception e) {
            }
            node.addEvent(event);
        }
    }

    private static class InterstitialAdCallback implements AdCallback {

        private final WeakReference<PictureTranslateListMainActivity> weakReference;

        public InterstitialAdCallback(PictureTranslateListMainActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        private void report(String type, String reason) {
            PictureTranslateListMainActivity activity = weakReference.get();
            if (null != activity) {
                activity.report(type, reason);
            }
        }

        private void sendAdShowMessage() {
            PictureTranslateListMainActivity activity = weakReference.get();
            if (null != activity) {
                activity.sendAdShowMessage();
            }
        }

        @Override
        public void onAdLoaded(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdShow(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            sendAdShowMessage();
        }

        @Override
        public void onAdError(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClick(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClose(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            LLog.w(TAG, "Interstitial close    ");
            Activity a = weakReference.get();
            if (a == null) {
                InitA.getInstance().cleanTask(PictureApplication.getApplication(), 7);
                return;
            }
            try {
                a.startActivity(new Intent(a, PictureTranslateResultActivity.class));
            } catch (Exception e) {
                //
            }
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            a.finish();
        }

        @Override
        public void onAdTimeOut(String type, String ad_type, String reason, long time) {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event != null && event.type == MessageEvent.UPDATE_HOME_DATA) {
            if (adapter != null && event.object instanceof PictureTranslateBean) {
                adapter.updateData((PictureTranslateBean) event.object);
                if (notData.getVisibility() != View.GONE) {
                    notData.setVisibility(View.GONE);
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        interstitialAdCallback = null;
        if (init == 0) {
            return;
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (allPermissionsGranted(grantResults)) {
                CameraActivity.startCameraActivity(this);
                if (animatorSet != null) {
                    animatorSet.cancel();
                }
                hintAnimText.setVisibility(View.GONE);
            } else {
                Toast.makeText(this, getString(R.string.app_toast_enable_permissions), Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == PICK_IMAGE_REQUEST) {
            if (allPermissionsGranted(grantResults)) {
                PermissionUtil.toSystemPhoto(this, PICK_IMAGE_REQUEST);
            } else {
                Toast.makeText(this, getString(R.string.app_toast_enable_permissions), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean allPermissionsGranted(int[] grantResults) {
        return grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
    }

    private void initView() {
        ImageView take_photo = findViewById(R.id.take_photo);
        take_photo.setOnClickListener(v -> checkSelfPermission());
        selectImg = findViewById(R.id.select_);
        selectImg.setOnClickListener(v -> {
            PermissionUtil.checkSelfIMAGEPermission(PictureTranslateListMainActivity.this, PICK_IMAGE_REQUEST);
        });
        recyclerView = findViewById(R.id.listData);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new PictureTranslateListAdapter(this, new ArrayList<>());
        recyclerView.setAdapter(adapter);
        notData = findViewById(R.id.not_data_layout);
        settingContent = findViewById(R.id.setting_content);
        setting = findViewById(R.id.setting);
        setting.setOnClickListener(v -> {
            setHomeAndSettingStatue(1);
        });
        home = findViewById(R.id.home);
        home.setSelected(true);
        home.setOnClickListener(v -> {
            setHomeAndSettingStatue(0);
        });
        title = findViewById(R.id.title);
        title.setText(getString(R.string.app_recent));
        hintAnimText = findViewById(R.id.hint);
        String first = SharedPreferencesUtil.getString(this, KEY_FIRST_CLK_TAKE_PHOTO, "");
        if (!TextUtils.isEmpty(first)) {
            hintAnimText.setVisibility(View.GONE);
        } else {
            startAnimation(hintAnimText);
        }
        delete = findViewById(R.id.delete);
        delete.setOnClickListener(v -> {
            showFragment(new DeleteFragment(), android.R.id.content);
        });
    }

    private void initData() {
        settingFragment = new SettingFragment();
        if (adapter.isDataEmpty()) {
            if (notData.getVisibility() != View.VISIBLE) {
                notData.setVisibility(View.VISIBLE);
            }
            return;
        }
        if (notData.getVisibility() != View.GONE) {
            notData.setVisibility(View.GONE);
        }
    }

    public void requestData() {
        ThreadUtils.startRunnable(() -> {
            List<PictureTranslateBean> arrayList = PictureApplication.getDataBaseManager().queryData();
            Collections.reverse(arrayList);
            runOnUiThread(() -> {
                adapter.updateData(arrayList);
                initData();
            });
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtils.e("intent:  " + intent);
        if (intent == null) {
            return;
        }
        PictureTranslateBean bean = (PictureTranslateBean) intent.getSerializableExtra("data");
        LogUtils.e("PictureTranslateBean:  " + bean);
        if (bean == null) {
            return;
        }
        if (adapter == null) {
            LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
            recyclerView.setLayoutManager(layoutManager);
            adapter = new PictureTranslateListAdapter(this, new ArrayList<>());
            recyclerView.setAdapter(adapter);
        }
        adapter.updateData(bean);
        LogUtils.e("updateData:  ");
        if (notData.getVisibility() != View.GONE) {
            notData.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(this, selectedImageUri);
        }
    }

    @Override
    public void onBackPressed() {
        if (init == 0) {
            return;
        }
        if (settingContent.getVisibility() == View.GONE) {
            super.onBackPressed();
        } else {
            setHomeAndSettingStatue(0);
        }
    }

    private void setHomeAndSettingStatue(int index) {
        switch (index) {
            case 0:
                if (settingContent.getVisibility() != View.GONE) {
                    settingContent.setVisibility(View.GONE);
                }
                title.setText(getString(R.string.app_recent));
                setting.setSelected(false);
                home.setSelected(true);
                if (delete.getVisibility() != View.VISIBLE) {
                    delete.setVisibility(View.VISIBLE);
                }
                if (selectImg.getVisibility() != View.VISIBLE) {
                    selectImg.setVisibility(View.VISIBLE);
                }
                break;
            case 1:
                setting.setSelected(true);
                home.setSelected(false);
                showFragment(settingFragment, R.id.setting_content);
                if (settingContent.getVisibility() != View.VISIBLE) {
                    settingContent.setVisibility(View.VISIBLE);
                }
                if (delete.getVisibility() != View.GONE) {
                    delete.setVisibility(View.GONE);
                }
                if (selectImg.getVisibility() != View.GONE) {
                    selectImg.setVisibility(View.GONE);
                }
                title.setText(getString(R.string.app_setting));
                break;
        }
    }

    private void startAnimation(TextView hint) {

        // 创建从下往上的动画
        ObjectAnimator moveUp = ObjectAnimator.ofFloat(hint, "translationY", 0, -20);
        moveUp.setInterpolator(new AccelerateInterpolator());
        moveUp.setDuration(500); // 位移时间0.5秒

        // 创建从上往下的动画
        ObjectAnimator moveDown = ObjectAnimator.ofFloat(hint, "translationY", -20, 0);
        moveDown.setInterpolator(new DecelerateInterpolator());
        moveDown.setDuration(500); // 位移时间0.5秒

        // 创建动画集合，包含从下往上和从上往下的动画
        animatorSet = new AnimatorSet();
        animatorSet.playSequentially(moveUp, moveDown);

        // 监听动画完成事件，以便可以再次触发动画
        animatorSet.addListener(new AnimatorSet.AnimatorListener() {
            @Override
            public void onAnimationStart(android.animation.Animator animation) {
            }

            @Override
            public void onAnimationEnd(android.animation.Animator animation) {
                animatorSet.start();
            }

            @Override
            public void onAnimationCancel(android.animation.Animator animation) {
            }

            @Override
            public void onAnimationRepeat(android.animation.Animator animation) {
            }
        });

        // 启动动画
        animatorSet.start();
    }

    /**
     * 检查权限
     */
    void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(this, PERMISSION_CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, PERMISSION_WRITE_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{PERMISSION_CAMERA, PERMISSION_WRITE_STORAGE}, REQUEST_CODE_PERMISSIONS);
        } else {
            CameraActivity.startCameraActivity(this);
            if (animatorSet != null) {
                animatorSet.cancel();
            }
            hintAnimText.setVisibility(View.GONE);
        }
    }

    public static void PictureTranslateListMainActivityStart(Context context) {
        Log.e("ACACACACA", "111");
//        Intent intent = new Intent(context, PictureTranslateListMainActivity.class);
//        context.startActivity(intent);
    }

    public static void PictureTranslateListMainActivityStart(Context context, PictureTranslateBean translateBean) {
        Intent intent = new Intent(context, PictureTranslateListMainActivity.class);
        intent.putExtra("data", translateBean);
        context.startActivity(intent);
    }

}
