package com.ads.cal.picturetranslate.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.ExperimentalGetImage;

import com.ads.cal.core.data.JumpInfo;
import com.ads.cal.core.utils.FragmentXUtils;
import com.ads.cal.core.views.fragments.JunkFragment;
import com.ads.cal.core.views.fragments.ProcessResultFragment;
import com.ads.cal.core.views.fragments.ProcessScanResultFragment;
import com.ads.cal.core.views.fragments.ResultFragment;
import com.ads.cal.picturetranslate.LogUtils;
import com.ads.cal.picturetranslate.MessageEvent;
import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.PictureTranslateUtils;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.ThreadUtils;
import com.ads.cal.picturetranslate.TopOnItAdManager;
import com.ads.cal.picturetranslate.Util;
import com.ads.cal.picturetranslate.base.BaseActivity;
import com.ads.cal.picturetranslate.bean.PictureTranslateBean;
import com.ads.cal.picturetranslate.fragment.LoadingFragment;
import com.gem.media.InitA;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.NativeAdClearManager;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.or.ange.dot.utils.LLog;

import org.greenrobot.eventbus.EventBus;
import java.util.Random;

@ExperimentalGetImage
public class PictureTranslateResultActivity extends BaseActivity {

    private static final String TAG = "PictureTranslateResultActivity";
    private ImageView imageView;
    private TextView result_txt;
    private PictureTranslateBean pictureTranslateBean;
    private LinearLayout moreSelectLayout;
    private ImageView standardImg, chineseImg, devanagariImg, japaneseImg, koreanImg;
    private TextView standardText, chineseImgText, devanagariText, japaneseText, koreanText;
    private Bitmap bitmap;
    private String path;
    private  final Handler handler = new Handler();


    public static void start(Activity activity, JumpInfo jumpInfo, int jumpType) {
        Intent intent;
        if (activity == null) {
            intent = new Intent(PictureApplication.getApplication(), PictureTranslateResultActivity.class);
        } else {
            intent = new Intent(activity, PictureTranslateResultActivity.class);
        }
        intent.putExtra(EXAM_DATA1, jumpInfo);
        intent.putExtra(EXAM_DATA2, jumpType);
        if (activity != null) {
            activity.startActivity(intent);
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PictureApplication.getApplication().startActivity(intent);
        }
        LLog.d(TAG, " jumpInfo "+jumpInfo.resultType+"  "+jumpInfo.junkCleanSize);
    }


    private ProcessScanResultFragment processScanResultFragment;
    private JunkFragment junkFragment;
    private ResultFragment resultFragment;
    private ProcessResultFragment processResultFragment;

    private void initClean(int jumpType) {
        Bundle bundle = new Bundle();
        JumpInfo jumpInfo = (JumpInfo) getIntent().getSerializableExtra(EXAM_DATA1);
        if (null != jumpInfo) {
            bundle.putSerializable("type", jumpInfo);
        }
        if (jumpType == JumpInfo.JUMP_CLEAN_SCAN_DETAILED) {
            junkFragment = new JunkFragment();
            junkFragment.setArguments(bundle);
            FragmentXUtils.replace(getSupportFragmentManager(), junkFragment, android.R.id.content);
            return;
        }
        if (jumpType == JumpInfo.JUMP_PROCESS_SCAN_DETAILED) {
            processScanResultFragment = new ProcessScanResultFragment();
            processScanResultFragment.setArguments(bundle);
            FragmentXUtils.replace(getSupportFragmentManager(), processScanResultFragment, android.R.id.content);
            return;
        }
//
        if (jumpType == JumpInfo.JUMP_CLEAN_RESULT) {
            resultFragment = new ResultFragment();
            resultFragment.setArguments(bundle);
            FragmentXUtils.replace(getSupportFragmentManager(), resultFragment, android.R.id.content);
            return;
        }
        if (jumpType == JumpInfo.JUMP_PROCESS_RESULT) {
            processResultFragment = new ProcessResultFragment();
            if (jumpInfo != null) {
                bundle.putInt("num", jumpInfo.stoppedPrecessNum);
            }
            processResultFragment.setArguments(bundle);
            FragmentXUtils.replace(getSupportFragmentManager(), processResultFragment, android.R.id.content);
            return;
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (init == 0) {
            Intent intent = getIntent();
            if (intent != null) {
                int jumpType = intent.getIntExtra(EXAM_DATA2, -1);
                if (jumpType != -1) {
                    initClean(jumpType);
                    return;
                }
            }
            moveTaskToBack(true);
            Random random = new Random();
            int d = random.nextInt(4) + 7;
            handler.removeCallbacksAndMessages(null);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, d * 1000);
            return;
        }
        setContentView(R.layout.activity_picture_translate_result);
        initView();
        initData();

        TopOnItAdManager.showItAd(this, null);
    }


    private String adPosition;
    private FrameLayout frameLayout;

    @Override
    protected void onStop() {
        super.onStop();
        if (init == 0) {
            if (null != processResultFragment) {
                adPosition = processResultFragment.getMAdPosition();
                frameLayout = processResultFragment.getNativeGroupView();
                return;
            }
            if (null != resultFragment) {
                adPosition = resultFragment.getMAdPosition();
                frameLayout = resultFragment.getNativeGroupView();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (init == 0) {
            if (null != frameLayout) {
                frameLayout.removeAllViews();
            }
            if (!TextUtils.isEmpty(adPosition)) {
                NativeAdClearManager manager = AdManager.getInstance().getNativeManager(adPosition);
                manager.destroyAd();
            }
        }
        handler.removeCallbacksAndMessages(null);
    }

    private void initView() {
        imageView = findViewById(R.id.image);
        LinearLayout back = findViewById(R.id.back);
        back.setOnClickListener(v -> {
            if (pictureTranslateBean != null && !TextUtils.isEmpty(pictureTranslateBean.getTitle())) {
                long time = System.currentTimeMillis();
                pictureTranslateBean.setNewTime(time);
                Toast.makeText(this, getString(R.string.app_save_automatically), Toast.LENGTH_SHORT).show();
                updateAndInsertData();
            }
            finish();
        });
        result_txt = findViewById(R.id.result_txt);
        result_txt.setMaxHeight((int) (Util.getScreenHeight(this) - (getResources().getDisplayMetrics().density * 300 + 0.5f)));
        TextView more_translate = findViewById(R.id.more);
        String text = getString(R.string.app_more_select);
        SpannableString spannableString = new SpannableString(text);
        // 添加点击事件
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                if (moreSelectLayout.getVisibility() != View.VISIBLE) {
                    moreSelectLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(true); // 添加下划线
                ds.setColor(Color.parseColor("#3E73DA")); // 设置文字颜色
            }
        };
        spannableString.setSpan(clickableSpan, 20, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 更改颜色
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#3E73DA"));
        spannableString.setSpan(colorSpan, 20, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 添加下划线
        UnderlineSpan underlineSpan = new UnderlineSpan();
        spannableString.setSpan(underlineSpan, 20, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        more_translate.setText(spannableString);
        more_translate.setMovementMethod(LinkMovementMethod.getInstance()); // 启用链接的点击事件
        more_translate.setHighlightColor(Color.TRANSPARENT); // 设置点击背景颜色为透明
        initSelectMoreView();
        LinearLayout share = findViewById(R.id.share);
        share.setOnClickListener(v -> {
            if (pictureTranslateBean == null) {
                return;
            }
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, pictureTranslateBean.getTitle()); // 设置要分享的内容
            startActivity(Intent.createChooser(shareIntent, getString(R.string.app_share_to)));
        });
        LinearLayout copy = findViewById(R.id.copy);
        copy.setOnClickListener(v -> {
            // 获取剪贴板管理器
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建剪贴板数据
            String textToCopy = result_txt.getText().toString();
            clipboard.setPrimaryClip(ClipData.newPlainText("text", textToCopy));

            // 提示用户已复制文本
            Toast.makeText(getApplicationContext(), getString(R.string.app_toast_copied), Toast.LENGTH_SHORT).show();
        });
    }

    private void initSelectMoreView() {
        moreSelectLayout = findViewById(R.id.more_select_layout);
        RelativeLayout standardLayout = findViewById(R.id.standard_layout);
        RelativeLayout chineseLayout = findViewById(R.id.chinese_layout);
        RelativeLayout devanagariLayout = findViewById(R.id.devanagari_layout);
        RelativeLayout japaneseLayout = findViewById(R.id.japanese_layout);
        RelativeLayout koreanLayout = findViewById(R.id.korean_layout);

        standardText = findViewById(R.id.standard_text);
        chineseImgText = findViewById(R.id.chinese_text);
        devanagariText = findViewById(R.id.devanagari_text);
        japaneseText = findViewById(R.id.japanese_text);
        koreanText = findViewById(R.id.korean_text);
        standardText.setTextColor(getColor(R.color.color_0075FF));
        standardImg = findViewById(R.id.standard_img);
        chineseImg = findViewById(R.id.chinese_img);
        devanagariImg = findViewById(R.id.devanagari_img);
        japaneseImg = findViewById(R.id.japanese_img);
        koreanImg = findViewById(R.id.korean_img);
        moreSelectLayout.setOnClickListener(v -> {
            if (moreSelectLayout.getVisibility() != View.GONE) {
                moreSelectLayout.setVisibility(View.GONE);
            }
        });
        standardLayout.setOnClickListener(v -> setCheck(0));
        chineseLayout.setOnClickListener(v -> setCheck(1));
        devanagariLayout.setOnClickListener(v -> setCheck(2));
        japaneseLayout.setOnClickListener(v -> setCheck(3));
        koreanLayout.setOnClickListener(v -> setCheck(4));
    }

    private void setCheck(int id) {
        switch (id) {
            case 0:
                standardImg.setVisibility(View.VISIBLE);
                chineseImg.setVisibility(View.GONE);
                devanagariImg.setVisibility(View.GONE);
                japaneseImg.setVisibility(View.GONE);
                koreanImg.setVisibility(View.GONE);
                standardText.setTextColor(getColor(R.color.color_0075FF));
                chineseImgText.setTextColor(getColor(R.color.black));
                devanagariText.setTextColor(getColor(R.color.black));
                japaneseText.setTextColor(getColor(R.color.black));
                koreanText.setTextColor(getColor(R.color.black));
                PictureTranslateUtils.init().translateStandard(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
            case 1:
                standardImg.setVisibility(View.GONE);
                chineseImg.setVisibility(View.VISIBLE);
                devanagariImg.setVisibility(View.GONE);
                japaneseImg.setVisibility(View.GONE);
                koreanImg.setVisibility(View.GONE);
                standardText.setTextColor(getColor(R.color.black));
                chineseImgText.setTextColor(getColor(R.color.color_0075FF));
                devanagariText.setTextColor(getColor(R.color.black));
                japaneseText.setTextColor(getColor(R.color.black));
                koreanText.setTextColor(getColor(R.color.black));
                PictureTranslateUtils.init().translateChinese(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
            case 2:
                standardImg.setVisibility(View.GONE);
                chineseImg.setVisibility(View.GONE);
                devanagariImg.setVisibility(View.VISIBLE);
                japaneseImg.setVisibility(View.GONE);
                koreanImg.setVisibility(View.GONE);
                standardText.setTextColor(getColor(R.color.black));
                chineseImgText.setTextColor(getColor(R.color.black));
                devanagariText.setTextColor(getColor(R.color.color_0075FF));
                japaneseText.setTextColor(getColor(R.color.black));
                koreanText.setTextColor(getColor(R.color.black));
                PictureTranslateUtils.init().translateDevanagari(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
            case 3:
                standardImg.setVisibility(View.GONE);
                chineseImg.setVisibility(View.GONE);
                devanagariImg.setVisibility(View.GONE);
                japaneseImg.setVisibility(View.VISIBLE);
                koreanImg.setVisibility(View.GONE);
                standardText.setTextColor(getColor(R.color.black));
                chineseImgText.setTextColor(getColor(R.color.black));
                devanagariText.setTextColor(getColor(R.color.black));
                japaneseText.setTextColor(getColor(R.color.color_0075FF));
                koreanText.setTextColor(getColor(R.color.black));
                PictureTranslateUtils.init().translateJapanese(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
            case 4:
                standardImg.setVisibility(View.GONE);
                chineseImg.setVisibility(View.GONE);
                devanagariImg.setVisibility(View.GONE);
                japaneseImg.setVisibility(View.GONE);
                koreanImg.setVisibility(View.VISIBLE);
                standardText.setTextColor(getColor(R.color.black));
                chineseImgText.setTextColor(getColor(R.color.black));
                devanagariText.setTextColor(getColor(R.color.black));
                japaneseText.setTextColor(getColor(R.color.black));
                koreanText.setTextColor(getColor(R.color.color_0075FF));
                PictureTranslateUtils.init().translateKorean(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
        }
        if (moreSelectLayout.getVisibility() != View.GONE) {
            moreSelectLayout.setVisibility(View.GONE);
        }
        showLoadingFragment(new LoadingFragment());
    }

    private void initData() {
        Intent intent = getIntent();
        if (null != intent) {
            pictureTranslateBean = (PictureTranslateBean) intent.getSerializableExtra("bean");
        }
        if (pictureTranslateBean == null) {
            return;
        }
        path = pictureTranslateBean.getImageUrl();
        bitmap = BitmapFactory.decodeFile(path);
        imageView.setImageBitmap(bitmap);
        result_txt.setText(pictureTranslateBean.getTitle());
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (init == 0) {
            if (junkFragment != null) {
                junkFragment.onBackPressed();
                return;
            }
            if (processScanResultFragment != null) {
                processScanResultFragment.onBackPressed();
                return;
            }
            super.onBackPressed();
            return;
        }
        if (pictureTranslateBean != null && !TextUtils.isEmpty(pictureTranslateBean.getTitle())) {
            long time = System.currentTimeMillis();
            pictureTranslateBean.setNewTime(time);
            Toast.makeText(this, getString(R.string.app_save_automatically), Toast.LENGTH_SHORT).show();
            updateAndInsertData();
        }
    }

    private void updateAndInsertData() {
        ThreadUtils.startRunnable(() -> {
            if (pictureTranslateBean.getTime() != 0) {
                PictureApplication.getDataBaseManager().deleteData(pictureTranslateBean.getTime());
            }
            PictureApplication.getDataBaseManager().insertData(path, pictureTranslateBean.getTitle(), pictureTranslateBean.getNewTime());
            runOnUiThread(() -> EventBus.getDefault().post(new MessageEvent(MessageEvent.UPDATE_HOME_DATA, pictureTranslateBean)));
        });//1695871418961

    }


    public static void startPictureTranslateResultActivity(Activity context, PictureTranslateBean bean) {
        TopOnItAdManager.showItAd(context, new TopOnItAdManager.OnItAdListener() {
            @Override
            public void onShow() {

            }

            @Override
            public void onClose() {
                Intent intent = new Intent(context, PictureTranslateResultActivity.class);
                intent.putExtra("bean", bean);
                context.startActivity(intent);
            }

            @Override
            public void onFail(String reason) {
                Intent intent = new Intent(context, PictureTranslateResultActivity.class);
                intent.putExtra("bean", bean);
                context.startActivity(intent);

            }
        });
    }

    private class MySuccessListener implements OnSuccessListener<Text> {

        @Override
        public void onSuccess(Text text) {
            LogUtils.e("AAAAAA", text.getText());
            result_txt.setText(text.getText());
            pictureTranslateBean.setTitle(text.getText());
            hideLoadingFragment();

        }
    }

    private class MyFailureListener implements OnFailureListener {


        @Override
        public void onFailure(@NonNull Exception e) {
            hideLoadingFragment();
        }
    }
}
