package com.datarecovery.master.module.filerecover;

import static com.datarecovery.master.data.consts.EventId.EVENT_3000003;

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

import androidx.annotation.Nullable;
import androidx.viewpager2.widget.ViewPager2;

import com.atmob.app.lib.base.BaseActivity;
import com.atmob.mediation.api.AdError;
import com.datarecovery.master.R;
import com.datarecovery.master.data.consts.AdFuncId;
import com.datarecovery.master.data.consts.Constants;
import com.datarecovery.master.data.consts.EventId;
import com.datarecovery.master.databinding.ActivityFileRecoverBinding;
import com.datarecovery.master.databinding.ItemTabFileRecoverBinding;
import com.datarecovery.master.dialog.CommonLoadingDialog;
import com.datarecovery.master.dialog.CommonSureDialog;
import com.datarecovery.master.dialog.ScanFileDialog;
import com.datarecovery.master.dialog.UnlockFunctionDialog;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.module.homepage.FunctionBean;
import com.datarecovery.master.sdk.ad.AtmobAdHelper;
import com.datarecovery.master.sdk.ad.RewardVideoListenerAdapter;
import com.datarecovery.master.utils.BoxingUtil;
import com.datarecovery.master.utils.CounterUtil;
import com.datarecovery.master.utils.FilePermissionHelper;
import com.datarecovery.master.utils.Maps;
import com.datarecovery.master.utils.ToastUtil;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class FileRecoverActivity extends BaseActivity<ActivityFileRecoverBinding> {

    private FileRecoverViewModel fileRecoverViewModel;

    private FileRecoverPageAdapter fileRecoverPageAdapter;
    private TabLayoutMediator tabLayoutMediator;

    private CommonLoadingDialog loadingDialog;
    private CommonSureDialog backDialog;
    private ScanFileDialog scanProgressDialog;
    private ViewPager2.OnPageChangeCallback onPageChangeCallback;
    private UnlockFunctionDialog unlockFunctionDialog;

    public static void start(Context context) {
        Intent intent = new Intent(context, FileRecoverActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

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

    private void initPermission() {
        new FilePermissionHelper().requestDataFilePermission(this, new FilePermissionHelper.NextStepCallback() {
            @Override
            public void onNextStep() {
                fileRecoverViewModel.startFileScanning();
            }

            @Override
            public void onCancel() {
                EventHelper.report(EVENT_3000003, Maps.asMap("id", 106));
                finish();
            }
        });
    }

    private void initObserver() {
        fileRecoverViewModel.getShowLoadingEvent().observe(this, this::showLoadingDialog);
        fileRecoverViewModel.getShowScanDialogEvent().observe(this, this::showScanProgressDialog);
        fileRecoverViewModel.getShowUnlockEvent().observe(this, this::showUnlockDialog);
    }

    private void showUnlockDialog(Object o) {
        if (unlockFunctionDialog == null) {
            unlockFunctionDialog = new UnlockFunctionDialog(this, FunctionBean.FILE_RECOVERY)
                    .setActionHandler(() -> AtmobAdHelper.showVideo(AdFuncId.REWARD_RECOVER, new RewardVideoListenerAdapter() {
                        boolean isRewarded = false;
                        @Override
                        public void onRewarded(@androidx.annotation.NonNull String token) {
                            super.onRewarded(token);
                            isRewarded = true;
                            fileRecoverViewModel.doExport();
                        }

                        @Override
                        public void onLoadFailed(AdError adError) {
                            super.onLoadFailed(adError);
                            fileRecoverViewModel.doExport();
                        }

                        @Override
                        public void onRewardAdShowFail(AdError adError) {
                            super.onRewardAdShowFail(adError);
                            fileRecoverViewModel.doExport();
                        }

                        @Override
                        public void onRewardAdClosed() {
                            super.onRewardAdClosed();
                            if (!isRewarded) {
                                ToastUtil.show(R.string.recover_failed, ToastUtil.LENGTH_SHORT);
                            }
                        }
                    }));
        }
        unlockFunctionDialog.show();
    }

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

    public void showLoadingDialog(Boolean show) {
        if (BoxingUtil.boxing(show)) {
            if (loadingDialog == null) {
                loadingDialog = new CommonLoadingDialog(this);
            }
            loadingDialog.show();
        } else {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
        }
    }

    public void showScanProgressDialog(Boolean show) {
        if (BoxingUtil.boxing(show)) {
            if (scanProgressDialog == null) {
                scanProgressDialog = new ScanFileDialog(this, fileRecoverViewModel.getDetectedLastFileName(), FunctionBean.FILE_RECOVERY);
                scanProgressDialog.setOnCancelListener(() -> fileRecoverViewModel.cancelScan());
            }
            scanProgressDialog.show();
        } else {
            if (scanProgressDialog != null) {
                scanProgressDialog.dismiss();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (!CounterUtil.checkAndIncrementByDay(Constants.KEY_LIST_BACK_AD_COUNTER, 2)) {
            AtmobAdHelper.showInterstitial(AdFuncId.INTERSTITIAL_RESULT_BACK, null);
        }
        showBackDialog();

        EventHelper.report(EventId.EVENT_3000002, Maps.asMap("id", 102));
    }

    @Override
    public void finish() {
        super.finish();
        EventHelper.report(EventId.EVENT_3000003, Maps.asMap("id", 103));
    }

    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.setOnShowListener(dialog -> EventHelper.report(EventId.EVENT_3000200, Maps.asMap("id", 102)));
        }
        backDialog.show();
    }

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

    private void initViewPager() {
        fileRecoverPageAdapter = new FileRecoverPageAdapter(this, fileRecoverViewModel.getTabTitle());
        binding.fileViewPager.setAdapter(fileRecoverPageAdapter);
        binding.fileViewPager.setOffscreenPageLimit(fileRecoverViewModel.getTabTitle().length);
        onPageChangeCallback = new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                fileRecoverViewModel.setCheckPosition(position);
            }
        };
        binding.fileViewPager.registerOnPageChangeCallback(onPageChangeCallback);
    }

    private void initTabLayout() {
        tabLayoutMediator = new TabLayoutMediator(binding.tabLayout, binding.fileViewPager, true, true, (tab, position) -> {
            int id = fileRecoverViewModel.getTabTitle()[position];
            ItemTabFileRecoverBinding binding = ItemTabFileRecoverBinding.inflate(getLayoutInflater());
            binding.setLifecycleOwner(this);
            if (id != 0) {
                binding.setTitle(id);
            }
            tab.view.setClipChildren(false);
            tab.view.setClipToPadding(false);
            tab.setCustomView(binding.getRoot());
            tab.setTag(binding);
        });
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                ViewGroup parent = (ViewGroup) tab.view.getParent();
                if (parent != null) {
                    parent.setClipChildren(false);
                    parent.setClipToPadding(false);
                }
                Object tag = tab.getTag();
                ItemTabFileRecoverBinding binding = tag instanceof ItemTabFileRecoverBinding ? ((ItemTabFileRecoverBinding) tag) : null;
                if (binding != null) {
                    binding.setIsCheck(true);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                Object tag = tab.getTag();
                ItemTabFileRecoverBinding binding = tag instanceof ItemTabFileRecoverBinding ? ((ItemTabFileRecoverBinding) tag) : null;
                if (binding != null) {
                    binding.setIsCheck(false);
                }
            }

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

            }
        });
        tabLayoutMediator.attach();
    }


    @Override
    protected void initViewModel() {
        super.initViewModel();
        fileRecoverViewModel = getViewModelProvider().get(FileRecoverViewModel.class);
        binding.setFileRecoverViewModel(fileRecoverViewModel);
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding.fileViewPager.unregisterOnPageChangeCallback(onPageChangeCallback);
    }
}
