package com.datarecovery.master.module.audiorecover;

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

import com.atmob.app.lib.base.BaseActivity;
import com.atmob.common.ui.SizeUtil;
import com.datarecovery.master.R;
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.ScanProgressDialog;
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.Maps;
import com.datarecovery.master.utils.ReportUtil;
import com.gyf.immersionbar.ImmersionBar;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class AudioRecoverActivity extends BaseActivity<ActivityAudioRecoverBinding> {

    private static final String IS_TRIAL = "is_trial";
    private AudioRecoverViewModel audioRecoverViewModel;

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

    private AudioItemAdapter audioItemAdapter;

    private PopupWindow filterPopup;

    private int popupHeight;
    private CommonSureDialog showTrialExportFailDialog;
    private CommonSureDialog showTrialFinishDialog;


    public static void start(Context context, boolean isTrial) {
        Intent intent = new Intent(context, AudioRecoverActivity.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) {
            audioRecoverViewModel.setIsTrial(intent.getBooleanExtra(IS_TRIAL, false));
        }
    }

    private void initPermission() {
        new FilePermissionHelper().requestDataFilePermission(this, MemberType.APP_AUDIO_RECOVER, audioRecoverViewModel.isTrial(), new FilePermissionHelper.NextStepCallback() {
            @Override
            public void onNextStep() {
                audioRecoverViewModel.startAudioScanning();
            }

            @Override
            public void onCancel() {
                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) {
                PreviewActivity.startDocumentPreView(AudioRecoverActivity.this, PreviewActivity.TYPE_AUDIO, file, audioRecoverViewModel.isTrial());
            }
        });
        if (audioRecoverViewModel.isTrial()) {
            binding.ryAudioRecover.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    if (audioRecoverViewModel.isTrial()) {
                        audioRecoverViewModel.scrollPosition(linearLayoutManager.findFirstCompletelyVisibleItemPosition(), linearLayoutManager.findLastCompletelyVisibleItemPosition(), linearLayoutManager.getItemCount());
                    }
                }
            });
        }
    }

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

    private void showTrialFinishDialog() {
        if (showTrialFinishDialog == null) {
            showTrialFinishDialog = new CommonSureDialog(this);
            showTrialFinishDialog.setDialogTitle(getString(R.string.scanning_progress, 7))
                    .setDialogContent(getString(R.string.trial_scanning_finish_content, 7)).setSureText(R.string.dialog_trial_recover);
            showTrialFinishDialog.setOnDialogClickListener(() -> {
                audioRecoverViewModel.onTrialRecoverClick();
                EventHelper.report(EventId.hf1001121, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_AUDIO_RECOVER)));
            });
            showTrialFinishDialog.setOnDismissListener(dialog -> EventHelper.report(EventId.hf1001122, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_AUDIO_RECOVER))));
        }
        if (!showTrialFinishDialog.isShowing()) {
            EventHelper.report(EventId.hf1001118, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_AUDIO_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);
            showTrialFinishDialog.setOnDialogClickListener(() -> {
                audioRecoverViewModel.onTrialRecoverClick();
                EventHelper.report(EventId.hf1001123, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_AUDIO_RECOVER)));
            });
            showTrialFinishDialog.setOnDismissListener(dialog -> EventHelper.report(EventId.hf1001124, Maps.asMap(EventId.EVENT_ID, ReportUtil.getReportId(MemberType.APP_AUDIO_RECOVER))));

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

    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());
        }
        if (popupHeight == 0) {
            binding.vFilter.post(() -> {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                popupHeight = SizeUtil.getScreenHeight() - binding.vFilter.getBottom();
                filterPopup.setHeight(popupHeight);
                filterPopup.showAsDropDown(binding.vFilter, 0, 0);
            });
        } else {
            filterPopup.showAsDropDown(binding.vFilter, 0, 0);
        }

    }

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

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