package com.ads.cal.picturetranslate.activity;

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

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
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.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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@ExperimentalGetImage
public class PictureTranslateListMainActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
    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;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitivty_picture_translate);
        initView();
        initData();
        requestData();
        EventBus.getDefault().register(this);
    }

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

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        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 (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) {
        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);
    }

}
