package com.datarecovery.master.module.preview;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.widget.SeekBar;

import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager2.widget.ViewPager2;

import com.atmob.app.lib.base.BaseActivity;
import com.atmob.common.ui.SizeUtil;
import com.atmob.logging.AtmobLog;
import com.atmob.mediation.api.AdError;
import com.datarecovery.master.R;
import com.datarecovery.master.data.consts.AdFuncId;
import com.datarecovery.master.data.consts.EventId;
import com.datarecovery.master.databinding.ActivityPreviewBinding;
import com.datarecovery.master.dialog.UnlockFunctionDialog;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.module.homepage.FunctionBean;
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.FilesSearch;
import com.datarecovery.master.utils.ImageDeepDetector;
import com.datarecovery.master.utils.SafeMediaPlayer;
import com.datarecovery.master.utils.ToastUtil;
import com.gyf.immersionbar.ImmersionBar;

import java.lang.ref.WeakReference;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class PreviewActivity extends BaseActivity<ActivityPreviewBinding> {

    public static final int TYPE_IMG = 1;
    public static final int TYPE_VIDEO = 2;
    public static final int TYPE_AUDIO = 3;
    private PreviewViewModel previewViewModel;
    private MediaPlayer mediaPlayer;
    private ViewPager2.OnPageChangeCallback onPageChangeCallback;
    private UnlockFunctionDialog unlockFunctionDialog;

    public static void startImagePreView(Context context, List<ImageDeepDetector.ImageFile> imageFileList, int position) {
        Intent intent = new Intent(context, PreviewActivity.class);
        intent.putExtra("type", TYPE_IMG);
        intent.putExtra("position", position);
        PreviewViewModel.weakReference = new WeakReference<>(imageFileList);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void startDocumentPreView(Context context, @Type int type, FilesSearch.DocumentFile documentFile) {
        Intent intent = new Intent(context, PreviewActivity.class);
        intent.putExtra("type", type);
        PreviewViewModel.weakReference = new WeakReference<>(documentFile);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

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

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

    @Override
    protected void initViewModel() {
        previewViewModel = getViewModelProvider().get(PreviewViewModel.class);
        binding.setPreviewViewModel(previewViewModel);
    }

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

        AtmobAdHelper.showInterstitial(AdFuncId.INTERSTITIAL_PREVIEW, null);

        switch (previewViewModel.getType()) {
            case TYPE_IMG:
                EventHelper.report(EventId.EVENT_3000502);
                break;
            case TYPE_VIDEO:
                EventHelper.report(EventId.EVENT_3000701);
                break;
            case TYPE_AUDIO:
                EventHelper.report(EventId.EVENT_3000801);
                break;
        }
    }

    private void initObserver() {
        previewViewModel.getClickMediaPlayerEvent().observe(this, o -> toggleMediaPlayer());
        previewViewModel.getSeekBarProgress().observe(this, process -> mediaPlayer.seekTo(BoxingUtil.boxing(process)));
        previewViewModel.getRefreshAudioCurrentProgress().observe(this, o -> binding.previewAudioSeekbar.setProgress(mediaPlayer.getCurrentPosition()));
        previewViewModel.getShowUnlockEvent().observe(this, o -> showUnlockDialog());
    }

    private void toggleMediaPlayer() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        } else {
            mediaPlayer.start();
        }
        previewViewModel.setIsPlaying(mediaPlayer.isPlaying());
    }

    private void showUnlockDialog() {
        if (unlockFunctionDialog == null) {
            unlockFunctionDialog = new UnlockFunctionDialog(this, getFunctionByType(previewViewModel.getType()))
                    .setActionHandler(new UnlockFunctionDialog.ActionHandler() {
                        boolean isRewarded = false;

                        @Override
                        public void onUnlock() {
                            AtmobAdHelper.showVideo(AdFuncId.REWARD_RECOVER, new RewardVideoListenerAdapter() {
                                @Override
                                public void onRewarded(@NonNull String token) {
                                    super.onRewarded(token);
                                    isRewarded = true;
                                    previewViewModel.doExport();
                                }

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

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

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

    private int getFunctionByType(int type) {
        switch (type) {
            case TYPE_IMG:
                return FunctionBean.IMG_RECOVERY;
            case TYPE_VIDEO:
                return FunctionBean.VIDEO_RECOVERY;
            case TYPE_AUDIO:
                return FunctionBean.AUDIO_RECOVERY;
        }
        return 0;
    }

    private void initIntentData() {
        int type = getIntent().getIntExtra("type", 0);
        int position = getIntent().getIntExtra("position", 0);
        previewViewModel.setPreviewData(type, position);
        if (type == TYPE_IMG) {
            initImagePreviewPager();
        } else {
            if (type == TYPE_VIDEO || type == TYPE_AUDIO) {
                initMediaPlayer(previewViewModel.getUri());
            }
            if (type == TYPE_VIDEO) {
                initSurfaceView();
            }
        }
    }

    private void initSeekBar(MediaPlayer mediaPlayer) {
        binding.previewAudioSeekbar.setProgress(0);
        binding.previewAudioSeekbar.setMax(mediaPlayer.getDuration());
        binding.previewAudioSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                previewViewModel.setSeekbarChanging(true);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                previewViewModel.setSeekbarChanging(false);
                previewViewModel.setSeekbarTo(seekBar.getProgress());
            }
        });
        previewViewModel.startMediaTimer();
    }

    private void initView() {
        binding.previewHeader.setNavigationOnClickListener(v -> finish());
        addTopStatusBarHeight(binding.previewHeader);
    }

    private void initImagePreviewPager() {
        PreviewImagePagerAdapter imagePagerAdapter = new PreviewImagePagerAdapter(previewViewModel.getImagePreviewList());
        binding.previewViewPager.setAdapter(imagePagerAdapter);
        onPageChangeCallback = new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                previewViewModel.setPosition(position);
            }
        };
        binding.previewViewPager.registerOnPageChangeCallback(onPageChangeCallback);
        binding.previewViewPager.setCurrentItem(previewViewModel.getPosition(), false);
    }

    private void initSurfaceView() {
        SurfaceHolder holder = binding.previewVideo.getHolder();
        previewViewModel.setSurfaceCreated(false);
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                AtmobLog.i("PreviewActivity", "surfaceCreated: ");
                mediaPlayer.setDisplay(holder);
                previewViewModel.setSurfaceCreated(true);
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                AtmobLog.i("PreviewActivity", "surfaceDestroyed: ");
                previewViewModel.setSurfaceCreated(false);
                mediaPlayer.setDisplay(null);
            }
        });
    }

    private void initMediaPlayer(Uri uri) {
        mediaPlayer = new SafeMediaPlayer();
        try {
            mediaPlayer.setDataSource(this, uri);
            mediaPlayer.setOnPreparedListener(mediaPlayer -> {
                if (previewViewModel.getType() == TYPE_VIDEO) {
                    initVideo(mediaPlayer);
                } else if (previewViewModel.getType() == TYPE_AUDIO) {
                    initSeekBar(mediaPlayer);
                }
            });
            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                ToastUtil.show(R.string.preview_source_error, ToastUtil.LENGTH_SHORT);
                return false;
            });
            mediaPlayer.setOnCompletionListener(mp -> {
                if (previewViewModel.getType() == TYPE_VIDEO) {
                    previewViewModel.setIsPlaying(false);
                    previewViewModel.setIsPlayStart(false);
                } else if (previewViewModel.getType() == TYPE_AUDIO) {
                    mediaPlayer.seekTo(0);
                    previewViewModel.setIsPlaying(false);
                }
            });
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            AtmobLog.e("PreviewActivity", "initMediaPlayer: ", e);
            ToastUtil.show(R.string.preview_source_error, ToastUtil.LENGTH_SHORT);
        }
    }

    private void initVideo(MediaPlayer mediaPlayer) {
        int videoWidth = mediaPlayer.getVideoWidth();
        int screenWidth = SizeUtil.getScreenWidth();
        float scaleX = screenWidth / (videoWidth * 1f);
        int width = (int) (videoWidth * scaleX);
        int height = (int) (mediaPlayer.getVideoHeight() * scaleX);
        binding.previewVideo.resize(width, height);
        previewViewModel.startMediaTimer();
    }

    @Override
    public void finish() {
        super.finish();

        switch (previewViewModel.getType()) {
            case TYPE_IMG:
                EventHelper.report(EventId.EVENT_3000503);
                break;
            case TYPE_VIDEO:
                EventHelper.report(EventId.EVENT_3000702);
                break;
            case TYPE_AUDIO:
                EventHelper.report(EventId.EVENT_3000802);
                break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            toggleMediaPlayer();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) mediaPlayer.release();
        binding.previewViewPager.unregisterOnPageChangeCallback(onPageChangeCallback);
    }

    @IntDef({TYPE_IMG, TYPE_VIDEO, TYPE_AUDIO})
    @interface Type {
    }
}