package com.datarecovery.master.module.imgrecover;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.ConcatAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.atmob.app.lib.base.BaseActivity;
import com.datarecovery.master.R;
import com.datarecovery.master.databinding.ActivityImageRecoverBinding;
import com.datarecovery.master.databinding.ItemTabImageRecoverBinding;
import com.datarecovery.master.dialog.CommonLoadingDialog;
import com.datarecovery.master.dialog.CommonSureDialog;
import com.datarecovery.master.dialog.ScanProgressDialog;
import com.datarecovery.master.module.preview.PreviewActivity;
import com.datarecovery.master.utils.BoxingUtil;
import com.datarecovery.master.utils.FilePermissionHelper;
import com.datarecovery.master.utils.GridRecoverItemDecoration;
import com.datarecovery.master.utils.ImageDeepDetector;
import com.google.android.material.tabs.TabLayout;
import com.gyf.immersionbar.ImmersionBar;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class ImageRecoverActivity extends BaseActivity<ActivityImageRecoverBinding> implements ImageItemAdapter.onItemClick {


    private ConcatAdapter concatAdapter;

    @IntDef({Type.RECOVER, Type.DELETE})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Type {
        int RECOVER = 1;
        int DELETE = 2;
    }

    private static final String TYPE = "type";
    ImageRecoverViewModel imageRecoverViewModel;

    private final int[] tabTitle = {R.string.photo, R.string.wx, R.string.qq, R.string.other};

    private CommonSureDialog backDialog;
    private CommonSureDialog clearDialog;
    private CommonLoadingDialog loadingDialog;
    private ScanProgressDialog scanProgressDialog;
    private ImageItemAdapter photoAdapter;
    private ImageItemAdapter wxAdapter;
    private ImageItemAdapter qqAdapter;
    private ImageItemAdapter otherAdapter;
    private GridLayoutManager gridLayoutManager;

    public static void start(Context context, @Type int type) {
        Intent intent = new Intent(context, ImageRecoverActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(TYPE, type);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        initObserver();
        initPermission();
    }

    private void initPermission() {
        new FilePermissionHelper().requestDataFilePermission(this, (imageRecoverViewModel.getType() == Type.RECOVER) ? "hf11001" : "hf11013", new FilePermissionHelper.NextStepCallback() {
            @Override
            public void onNextStep() {
                imageRecoverViewModel.startImageScanning();
            }

            @Override
            public void onCancel() {
                finish();
            }
        });
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            imageRecoverViewModel.setOperationType(intent.getIntExtra(TYPE, Type.RECOVER));
        }
    }

    private void initView() {
        binding.toolBar.setNavigationOnClickListener(v -> onBackPressed());
        addTopStatusBarHeight(binding.toolBar);
        initRecycleView();
        initTabLayout();
    }

    private void initRecycleView() {
        ImageTitleAdapter photoTitleAdapter = new ImageTitleAdapter(this, imageRecoverViewModel.getDetectedPhotoTitle());
        photoAdapter = new ImageItemAdapter(ImageDeepDetector.ImageFile.CATEGORY_GALLERY, this);
        photoAdapter.setOnItemClick(this);

        ImageTitleAdapter wxTitleAdapter = new ImageTitleAdapter(this, imageRecoverViewModel.getDetectedWxTitle());
        wxAdapter = new ImageItemAdapter(ImageDeepDetector.ImageFile.CATEGORY_WECHAT, this);
        wxAdapter.setOnItemClick(this);

        ImageTitleAdapter qqTitleAdapter = new ImageTitleAdapter(this, imageRecoverViewModel.getDetectedQQTitle());
        qqAdapter = new ImageItemAdapter(ImageDeepDetector.ImageFile.CATEGORY_QQ, this);
        qqAdapter.setOnItemClick(this);

        ImageTitleAdapter otherTitleAdapter = new ImageTitleAdapter(this, imageRecoverViewModel.getDetectedOtherTitle());
        otherAdapter = new ImageItemAdapter(ImageDeepDetector.ImageFile.CATEGORY_OTHER, this);
        otherAdapter.setOnItemClick(this);

        concatAdapter = new ConcatAdapter(
                photoTitleAdapter,
                photoAdapter,
                wxTitleAdapter,
                wxAdapter,
                qqTitleAdapter,
                qqAdapter,
                otherTitleAdapter,
                otherAdapter
        );
        binding.ryImageRecover.setAdapter(concatAdapter);
        gridLayoutManager = new GridLayoutManager(this, 3);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == getPhotoPosition() || position == getWxPosition() || position == getQQPosition() || position == getOtherPosition()) {
                    return 3;
                }
                return 1;
            }
        });
        binding.ryImageRecover.addItemDecoration(new GridRecoverItemDecoration(3, 0.0282222222222222f, 0.0202222222222222f));
        binding.ryImageRecover.setLayoutManager(gridLayoutManager);

        RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                int firstVisibleItem = gridLayoutManager.findFirstVisibleItemPosition();
                int lastVisibleItem = gridLayoutManager.findLastVisibleItemPosition();

                int photoPosition = getPhotoPosition();
                int wxPosition = getWxPosition();
                int qqPosition = getQQPosition();
                int otherPosition = getOtherPosition();
                if (firstVisibleItem == photoPosition || (firstVisibleItem >= photoPosition && lastVisibleItem < wxPosition)) {
                    binding.tabLayout.selectTab(binding.tabLayout.getTabAt(0));
                } else if (firstVisibleItem == wxPosition || (firstVisibleItem >= wxPosition && lastVisibleItem < qqPosition)) {
                    binding.tabLayout.selectTab(binding.tabLayout.getTabAt(1));
                } else if (firstVisibleItem == qqPosition || (firstVisibleItem >= qqPosition && lastVisibleItem < otherPosition)) {
                    binding.tabLayout.selectTab(binding.tabLayout.getTabAt(2));
                } else if (firstVisibleItem >= otherPosition) {
                    binding.tabLayout.selectTab(binding.tabLayout.getTabAt(3));
                }
            }
        };
        binding.ryImageRecover.addOnScrollListener(onScrollListener);
    }

    public int getPhotoPosition() {
        return 0;
    }

    public int getWxPosition() {
        return getPhotoPosition() + photoAdapter.getItemCount() + 1;
    }

    public int getQQPosition() {
        return getWxPosition() + wxAdapter.getItemCount() + 1;
    }

    public int getOtherPosition() {
        return getQQPosition() + qqAdapter.getItemCount() + 1;
    }

    @Override
    public void onCheck(ImageDeepDetector.ImageFile imageFile) {
        if (imageFile == null) {
            return;
        }
        imageRecoverViewModel.setItemCheck(imageFile);
    }

    @Override
    public void onItemClick(ImageDeepDetector.ImageFile imageFile) {
        if (imageFile == null) {
            return;
        }
        if (imageRecoverViewModel.getType() == Type.DELETE) {
            imageRecoverViewModel.setItemCheck(imageFile);
        } else {
            imageRecoverViewModel.checkPreview(imageFile);
        }

    }

    private void initTabLayout() {
        binding.tabLayout.removeAllTabs();
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getCustomView() == null) {
                    return;
                }
                ItemTabImageRecoverBinding itemBinding = ItemTabImageRecoverBinding.bind(tab.getCustomView());
                itemBinding.tabTitle.setTextColor(getResources().getColor(com.atmob.app.base.R.color.white));
                itemBinding.tabTitle.setBackground(getResources().getDrawable(R.drawable.bg_tab_selected));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab.getCustomView() == null) {
                    return;
                }
                ItemTabImageRecoverBinding itemBinding = ItemTabImageRecoverBinding.bind(tab.getCustomView());
                itemBinding.tabTitle.setTextColor(getResources().getColor(R.color.tab_un_select_text_color));
                itemBinding.tabTitle.setBackground(null);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        for (int i = 0; i < tabTitle.length; i++) {
            TabLayout.Tab tab = binding.tabLayout.newTab();
            ItemTabImageRecoverBinding tabLayoutBinding = ItemTabImageRecoverBinding.inflate(getLayoutInflater());
            int finalI = i;
            tabLayoutBinding.getRoot().setOnClickListener(v -> {
                switch (finalI) {
                    case 0:
                        gridLayoutManager.scrollToPositionWithOffset(getPhotoPosition(), 0);
                        break;
                    case 1:
                        gridLayoutManager.scrollToPositionWithOffset(getWxPosition(), 0);
                        break;
                    case 2:
                        gridLayoutManager.scrollToPositionWithOffset(getQQPosition(), 0);
                        break;
                    case 3:
                        gridLayoutManager.scrollToPositionWithOffset(getOtherPosition(), 0);
                        break;
                }
                binding.tabLayout.selectTab(binding.tabLayout.getTabAt(finalI));
            });
            tabLayoutBinding.tabTitle.setText(tabTitle[i]);
            tab.setCustomView(tabLayoutBinding.getRoot());
            binding.tabLayout.addTab(tab);
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private void initObserver() {
        imageRecoverViewModel.getNotifyList().observe(this, o -> {
            photoAdapter.notifyDataSetChanged();
            wxAdapter.notifyDataSetChanged();
            qqAdapter.notifyDataSetChanged();
            otherAdapter.notifyDataSetChanged();
        });
        imageRecoverViewModel.getShowScanDialogEvent().observe(this, this::showScanProgressDialog);
        imageRecoverViewModel.getDetectedPhotoImg().observe(this, list -> photoAdapter.submit(list));
        imageRecoverViewModel.getDetectedWxImg().observe(this, list -> wxAdapter.submit(list));
        imageRecoverViewModel.getDetectedQQImg().observe(this, list -> qqAdapter.submit(list));
        imageRecoverViewModel.getDetectedOtherImg().observe(this, list -> otherAdapter.submit(list));
        imageRecoverViewModel.getDetectedFinish().observe(this, o -> scanProgressDialog.detectedFinish());
        imageRecoverViewModel.getPreviewEvent().observe(this, imageFile -> {
            List<ImageDeepDetector.ImageFile> allDetectedList = imageRecoverViewModel.getAllDetectedList();
            int position = imageRecoverViewModel.getPosition(allDetectedList, imageFile);
            PreviewActivity.startImagePreView(this, allDetectedList, position);
        });
        imageRecoverViewModel.getShowLoadingEvent().observe(this, this::showLoadingDialog);
        imageRecoverViewModel.getShowClearDialog().observe(this, o -> showClearDialog());
    }

    private void showClearDialog() {
        if (clearDialog == null) {
            clearDialog = new CommonSureDialog(this);
            clearDialog.setDialogTitle(R.string.img_clear_sure_title).setDialogContent(R.string.img_clear_sure_content);
            clearDialog.setOnDialogClickListener(() -> imageRecoverViewModel.executeImageDelete());
        }
        clearDialog.show();
    }

    private void showBackDialog() {
        if (backDialog == null) {
            backDialog = new CommonSureDialog(this);
            backDialog.setDialogTitle(R.string.img_recovery_back_title)
                    .setDialogContent(R.string.img_recovery_back_content)
                    .setOnDialogClickListener(this::finish);
        }
        backDialog.show();
    }

    @Override
    protected void configImmersion(@NonNull ImmersionBar immersionBar) {
        immersionBar.statusBarDarkFont(true);
    }

    public void showScanProgressDialog(Boolean show) {
        if (BoxingUtil.boxing(show)) {
            if (scanProgressDialog == null) {
                scanProgressDialog = new ScanProgressDialog(this, imageRecoverViewModel.getTotalDetectedCount());
                scanProgressDialog.setOnCancelListener(() -> imageRecoverViewModel.cancelScan());
            }
            scanProgressDialog.show();
        } else {
            if (scanProgressDialog != null) {
                scanProgressDialog.dismiss();
            }
        }
    }

    public void showLoadingDialog(Boolean show) {
        if (BoxingUtil.boxing(show)) {
            if (loadingDialog == null) {
                loadingDialog = new CommonLoadingDialog(this);
                loadingDialog.setMessage((imageRecoverViewModel.getType()) == Type.DELETE ? R.string.deleting : R.string.exporting);
            }
            loadingDialog.show();
        } else {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
        }
    }

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

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


    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.tabLayout.clearOnTabSelectedListeners();
    }

    @Override
    protected boolean shouldImmersion() {
        return true;
    }

    @Override
    protected void initViewModel() {
        super.initViewModel();
        imageRecoverViewModel = getViewModelProvider().get(ImageRecoverViewModel.class);
        binding.setImageRecoverViewModel(imageRecoverViewModel);
    }

}
