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.datarecovery.master.databinding.ActivityPreviewBinding;
import com.datarecovery.master.utils.FilesSearch;
import com.datarecovery.master.utils.ImageDeepDetector;
import com.datarecovery.master.utils.SafeMediaPlayer;
import com.gyf.immersionbar.ImmersionBar;

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

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 boolean isSurfaceCreated;

    private Timer timer;
    private boolean isSeekbarChanging;

    private ViewPager2.OnPageChangeCallback onPageChangeCallback;

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

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

    private void initObserver() {

    }

    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() {
        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) {
                isSeekbarChanging = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekbarChanging = false;
                mediaPlayer.seekTo(seekBar.getProgress());
            }
        });
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!isSeekbarChanging) {
                    binding.previewAudioSeekbar.setProgress(mediaPlayer.getCurrentPosition());
                }
            }
        }, 0, 100);
    }

    private void initView() {
        binding.previewHeader.setNavigationOnClickListener(v -> finish());
        addTopStatusBarHeight(binding.previewHeader);
        binding.previewVideoContainer.setOnClickListener(v -> {
            if (isSurfaceCreated) {
                previewViewModel.setIsPlayStart();
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                } else {
                    mediaPlayer.start();
                }
                previewViewModel.setIsPlaying(mediaPlayer.isPlaying());
            }
        });
        binding.previewAudioPlay.setOnClickListener(v -> {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            } else {
                mediaPlayer.start();
            }
            previewViewModel.setIsPlaying(mediaPlayer.isPlaying());
        });
    }

    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();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                mediaPlayer.setDisplay(holder);
                isSurfaceCreated = true;
            }

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

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                mediaPlayer.stop();
                mediaPlayer.setDisplay(null);
            }
        });
    }

    private void initMediaPlayer(Uri uri) {
        mediaPlayer = new SafeMediaPlayer();
        try {
            mediaPlayer.setDataSource(this, uri);
            mediaPlayer.setOnPreparedListener(mp -> {
                if (previewViewModel.getType() == TYPE_VIDEO) {
                    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);
                } else if (previewViewModel.getType() == TYPE_AUDIO) {
                    initSeekBar();
                }
            });
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnCompletionListener(mp -> {
                if (previewViewModel.getType() == TYPE_VIDEO) {
                    previewViewModel.setIsPlaying(false);
                } else if (previewViewModel.getType() == TYPE_AUDIO) {
                    mediaPlayer.seekTo(0);
                    previewViewModel.setIsPlaying(false);
                }
            });
        } catch (Exception ignored) {
        }
    }

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