package com.datarecovery.master.module.audiorecover;

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

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 android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.atmob.app.lib.base.BaseActivity;
import com.atmob.common.ui.SizeUtil;
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.ActivityAudioRecoverBinding;
import com.datarecovery.master.databinding.PopupAudioRecoverFilterBinding;
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.Maps;
import com.datarecovery.master.utils.ToastUtil;
import com.gyf.immersionbar.ImmersionBar;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class AudioRecoverActivity extends BaseActivity<ActivityAudioRecoverBinding> {

    private AudioRecoverViewModel audioRecoverViewModel;

    private CommonLoadingDialog loadingDialog;
    private CommonSureDialog backDialog;
    private ScanFileDialog scanFileDialog;

    private AudioItemAdapter audioItemAdapter;

    private PopupWindow filterPopup;

    private UnlockFunctionDialog unlockFunctionDialog;

    public static void start(Context context) {
        Intent intent = new Intent(context, AudioRecoverActivity.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() {
                audioRecoverViewModel.startAudioScanning();
            }

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

    private void initView() {
        addTopStatusBarHeight(binding.toolBar);
        binding.toolBar.setNavigationOnClickListener(v -> onBackPressed());
        audioItemAdapter = new AudioItemAdapter(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseContext());
        binding.ryAudioRecover.setLayoutManager(linearLayoutManager);
        binding.ryAudioRecover.setAdapter(audioItemAdapter);
        audioItemAdapter.setOnItemClick(new AudioItemAdapter.onItemClick() {
            @Override
            public void onCheck(FilesSearch.DocumentFile file) {
                if (file == null) {
                    return;
                }
                audioRecoverViewModel.setItemCheck(file);
            }

            @Override
            public void onItemClick(FilesSearch.DocumentFile file) {
                EventHelper.report(EventId.EVENT_3000800);
                PreviewActivity.startDocumentPreView(AudioRecoverActivity.this, PreviewActivity.TYPE_AUDIO, file);
            }
        });
    }

    @SuppressLint("NotifyDataSetChanged")
    private void initObserver() {
        audioRecoverViewModel.getScrollTop().observe(this, o -> binding.ryAudioRecover.scrollToPosition(0));
        audioRecoverViewModel.getShowLoadingEvent().observe(this, this::showLoadingDialog);
        audioRecoverViewModel.getNotifyAudioData().observe(this, o -> audioItemAdapter.notifyDataSetChanged());
        audioRecoverViewModel.getDetectedVideoList().observe(this, list -> audioItemAdapter.submit(list));
        audioRecoverViewModel.getShowScanDialogEvent().observe(this, this::showScanProgressDialog);
        audioRecoverViewModel.getShowFilterPopup().observe(this, o -> showFilterPopup());
        audioRecoverViewModel.getShowUnlockEvent().observe(this, o -> showUnlockDialog());
    }

    private void showUnlockDialog() {
        if (unlockFunctionDialog == null) {
            unlockFunctionDialog = new UnlockFunctionDialog(this, FunctionBean.AUDIO_RECOVERY)
                    .setActionHandler(new UnlockFunctionDialog.ActionHandler() {
                        @Override
                        public void onUnlock() {
                            AtmobAdHelper.showVideo(AdFuncId.REWARD_RECOVER, new RewardVideoListenerAdapter() {
                                boolean isRewarded = false;

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

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

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

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

    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 showFilterPopup() {
        if (filterPopup == null) {
            PopupAudioRecoverFilterBinding audioRecoverFilterBinding = PopupAudioRecoverFilterBinding.inflate(LayoutInflater.from(getBaseContext()));
            int[] dateFilterArray = audioRecoverViewModel.getDateFilterArray();
            audioRecoverFilterBinding.llFilterContainer.removeAllViews();
            int leftPadding = (int) (SizeUtil.dp2px(41));
            int verPadding = (int) (SizeUtil.dp2px(10));
            audioRecoverFilterBinding.getRoot().setOnClickListener(v -> filterPopup.dismiss());
            for (int txt : dateFilterArray) {
                TextView filterTv = new TextView(getBaseContext());
                filterTv.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                filterTv.setPadding(leftPadding, verPadding, 0, verPadding);
                filterTv.setText(txt);
                filterTv.setTextSize(14);
                filterTv.setBackgroundResource(R.drawable.bg_ripple_common_mask);
                filterTv.setTextColor(getResources().getColor(R.color.color_404040));
                filterTv.setOnClickListener(v -> {
                    audioRecoverViewModel.setFilter(txt);
                    filterPopup.dismiss();
                });
                audioRecoverFilterBinding.llFilterContainer.addView(filterTv);
            }
            filterPopup = new PopupWindow(audioRecoverFilterBinding.getRoot(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            filterPopup.setOutsideTouchable(true);
            filterPopup.setFocusable(true);
            filterPopup.setOnDismissListener(() -> audioRecoverViewModel.setIsDateFilterArrowDown());
        }
        binding.vFilter.post(() -> {
            if (isFinishing() || isDestroyed()) {
                return;
            }
            filterPopup.showAsDropDown(binding.vFilter, 0, 0);
        });
    }

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

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

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

    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", 104)));
        }
        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 configImmersion(@NonNull ImmersionBar immersionBar) {
        immersionBar.statusBarDarkFont(true);
    }

    @Override
    protected void initViewModel() {
        super.initViewModel();
        audioRecoverViewModel = getViewModelProvider().get(AudioRecoverViewModel.class);
        binding.setAudioRecoverViewModel(audioRecoverViewModel);
    }

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