package com.datarecovery.master.module.videorecover;

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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

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.ActivityVideoRecoverBinding;
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.module.preview.PreviewActivity;
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.FilesSearch;
import com.datarecovery.master.utils.GridRecoverItemDecoration;
import com.datarecovery.master.utils.Maps;
import com.datarecovery.master.utils.ToastUtil;
import com.gyf.immersionbar.ImmersionBar;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class VideoRecoverActivity extends BaseActivity<ActivityVideoRecoverBinding> {

    private static final String IS_TRIAL = "is_trial";
    private VideoRecoverViewModel videoRecoverViewModel;
    private CommonLoadingDialog loadingDialog;
    private CommonSureDialog backDialog;
    private ScanFileDialog scanFileDialog;
    private VideoItemAdapter videoItemAdapter;
    private UnlockFunctionDialog unlockFunctionDialog;

    public static void start(Context context) {
        Intent intent = new Intent(context, VideoRecoverActivity.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);
        initData();
        initView();
        initObserver();
        initPermission();
    }

    private void initData() {

    }

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

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

    private void initObserver() {
        videoRecoverViewModel.getShowLoadingEvent().observe(this, this::showLoadingDialog);
        videoRecoverViewModel.getDetectedVideoList().observe(this, list -> videoItemAdapter.submit(list));
        videoRecoverViewModel.getScrollTop().observe(this, o -> binding.ryVideoRecover.scrollToPosition(0));
        videoRecoverViewModel.getShowScanDialogEvent().observe(this, this::showScanProgressDialog);
        videoRecoverViewModel.getShowUnlockEvent().observe(this, o -> showUnlockDialog());
    }

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

    private void showUnlockDialog() {
        if (unlockFunctionDialog == null) {
            unlockFunctionDialog = new UnlockFunctionDialog(this, FunctionBean.VIDEO_RECOVERY)
                    .setActionHandler(() -> AtmobAdHelper.showVideo(AdFuncId.REWARD_RECOVER, new RewardVideoListenerAdapter() {
                        boolean isRewarded = false;

                        @Override
                        public void onRewarded(@NonNull String token) {
                            super.onRewarded(token);
                            isRewarded = true;
                            videoRecoverViewModel.doExport();
                        }

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

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

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

    private void initRecycleView() {
        videoItemAdapter = new VideoItemAdapter(this);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        binding.ryVideoRecover.setLayoutManager(gridLayoutManager);
        binding.ryVideoRecover.setAdapter(videoItemAdapter);
        binding.ryVideoRecover.addItemDecoration(new GridRecoverItemDecoration(3, 0.0282222222222222f, 0.0202222222222222f));
        videoItemAdapter.setOnItemClick(new VideoItemAdapter.onItemClick() {
            @Override
            public void onCheck(FilesSearch.DocumentFile file) {
                if (file == null) {
                    return;
                }
                videoRecoverViewModel.setItemCheck(file);
            }

            @Override
            public void onItemClick(FilesSearch.DocumentFile file) {
                PreviewActivity.startDocumentPreView(VideoRecoverActivity.this, PreviewActivity.TYPE_VIDEO, file);
                EventHelper.report(EventId.EVENT_3000700);
            }
        });
    }

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

    public void showLoadingDialog(Boolean show) {
        if (BoxingUtil.boxing(show)) {
            if (loadingDialog == null) {
                loadingDialog = new CommonLoadingDialog(this);
            }
            loadingDialog.show();
        } else {
            if (loadingDialog != null) {
                loadingDialog.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", 103));
    }

    @Override
    public void finish() {
        super.finish();
        EventHelper.report(EventId.EVENT_3000002, 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", 103)));
        }
        backDialog.show();
    }

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

    @Override
    protected void initViewModel() {
        super.initViewModel();
        videoRecoverViewModel = getViewModelProvider().get(VideoRecoverViewModel.class);
        binding.setVideoRecoverViewModel(videoRecoverViewModel);
    }

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

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