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 com.atmob.app.lib.base.BaseActivity;
import com.atmob.common.ui.SizeUtil;
import com.datarecovery.master.R;
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.ScanProgressDialog;
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.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 ScanProgressDialog scanProgressDialog;

    private AudioItemAdapter audioItemAdapter;

    private PopupWindow filterPopup;

    private int popupHeight;


    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, "hf11007", 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);
        binding.ryAudioRecover.setLayoutManager(new LinearLayoutManager(getBaseContext()));
        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);
            }
        });
    }

    @SuppressLint("NotifyDataSetChanged")
    private void initObserver() {
        audioRecoverViewModel.getShowLoadingEvent().observe(this, this::showLoadingDialog);
        audioRecoverViewModel.getNotifyAudioData().observe(this, o -> audioItemAdapter.notifyDataSetChanged());
        audioRecoverViewModel.getDetectedVideoList().observe(this, list -> audioItemAdapter.submit(list));
        audioRecoverViewModel.getDetectedFinish().observe(this, o -> scanProgressDialog.detectedFinish());
        audioRecoverViewModel.getShowScanDialogEvent().observe(this, this::showScanProgressDialog);
        audioRecoverViewModel.getShowFilterPopup().observe(this, o -> showFilterPopup());
    }

    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 (scanProgressDialog == null) {
                scanProgressDialog = new ScanProgressDialog(this, audioRecoverViewModel.getTotalDetectedCount());
                scanProgressDialog.setOnCancelListener(() -> audioRecoverViewModel.cancelScan());
            }
            scanProgressDialog.show();
        } else {
            if (scanProgressDialog != null) {
                scanProgressDialog.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;
    }
}
