package com.datarecovery.master.module.videorecover;

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 androidx.recyclerview.widget.RecyclerView;

import com.atmob.app.lib.base.BaseActivity;
import com.datarecovery.master.R;
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.handler.EventHelper;
import com.datarecovery.master.module.member.MemberType;
import com.datarecovery.master.module.preview.PreviewActivity;
import com.datarecovery.master.utils.BoxingUtil;
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.ReportUtil;
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 CommonSureDialog showTrialExportFailDialog;
    private CommonSureDialog showTrialFinishDialog;


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

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

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            videoRecoverViewModel.setIsTrial(intent.getBooleanExtra(IS_TRIAL, false));
        }
    }

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

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

    private void initObserver() {
        videoRecoverViewModel.getShowTrialFinishDialog().observe(this, o -> showTrialFinishDialog());
        videoRecoverViewModel.getShowTrialExportFailDialog().observe(this, o -> showTrialExportFailDialog());
        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);
    }

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

    private void showTrialFinishDialog() {
        if (showTrialFinishDialog == null) {
            showTrialFinishDialog = new CommonSureDialog(this);
            showTrialFinishDialog.setDialogTitle(getString(R.string.scanning_progress, 8))
                    .setDialogContent(getString(R.string.trial_scanning_finish_content, 8)).setSureText(R.string.dialog_trial_recover);
            showTrialFinishDialog.setOnDialogClickListener(() -> {
                videoRecoverViewModel.onTrialRecoverClick();
                EventHelper.report(EventId.hf1001121, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_VIDEO_RECOVER)));
            });
            showTrialFinishDialog.setOnDismissListener(dialog -> EventHelper.report(EventId.hf1001122, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_VIDEO_RECOVER))));
        }
        if (!showTrialFinishDialog.isShowing()) {
            EventHelper.report(EventId.hf1001118, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_VIDEO_RECOVER)));
            showTrialFinishDialog.show();
        }
    }

    private void showTrialExportFailDialog() {
        if (showTrialExportFailDialog == null) {
            showTrialExportFailDialog = new CommonSureDialog(this);
            showTrialExportFailDialog.setDialogTitle(R.string.trial_export_fail_title)
                    .setDialogContent(R.string.trial_export_fail_content).setSureText(R.string.dialog_trial_recover);
            showTrialExportFailDialog.setOnDialogClickListener(() -> {
                videoRecoverViewModel.onTrialRecoverClick();
                EventHelper.report(EventId.hf1001123, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_VIDEO_RECOVER)));
            });
            showTrialExportFailDialog.setOnDismissListener(dialog -> EventHelper.report(EventId.hf1001124, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_VIDEO_RECOVER))));

        }
        if (!showTrialExportFailDialog.isShowing()) {
            showTrialExportFailDialog.show();
            EventHelper.report(EventId.hf1001120, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_VIDEO_RECOVER)));
        }
    }

    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, videoRecoverViewModel.isTrial());
            }
        });
        if (videoRecoverViewModel.isTrial()) {
            binding.ryVideoRecover.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    if (videoRecoverViewModel.isTrial()) {
                        videoRecoverViewModel.scrollPosition(gridLayoutManager.findFirstCompletelyVisibleItemPosition(), gridLayoutManager.findLastCompletelyVisibleItemPosition(), gridLayoutManager.getItemCount());
                    }
                }
            });
            binding.ryVideoRecover.setOnFlingListener(new RecyclerView.OnFlingListener() {
                @Override
                public boolean onFling(int velocityX, int velocityY) {
                    int firstCompletelyVisibleItemPosition = gridLayoutManager.findFirstCompletelyVisibleItemPosition();
                    if ((firstCompletelyVisibleItemPosition == -1 && velocityY > 0) || (gridLayoutManager.findFirstCompletelyVisibleItemPosition() == 0 && gridLayoutManager.findLastCompletelyVisibleItemPosition() == gridLayoutManager.getItemCount() - 1 && velocityY > 0)) {
                        showTrialFinishDialog();
                        return true;
                    }
                    return false;
                }
            });
        }
    }

    public void showScanProgressDialog(Boolean show) {
        if (BoxingUtil.boxing(show)) {
            if (scanFileDialog == null) {
                scanFileDialog = new ScanFileDialog(this, videoRecoverViewModel.getDetectedLastFileName());
                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() {
        showBackDialog();
    }

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