package com.unibuy.smartdevice.ui.tools;

import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;

import androidx.annotation.OptIn;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.source.MediaSource;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;
import androidx.media3.extractor.DefaultExtractorsFactory;
import androidx.media3.ui.PlayerView;

import com.bumptech.glide.Glide;

import java.util.List;

public class VideoImageMixedPlayerOptimized {
    private final Context context;
    private final List<String> mediaUrls;
    private ExoPlayer exoPlayer;
    private PlayerView videoView;
    private ImageView imageView;
    private Handler imageHandler;
    private int currentIndex = 0;

    public VideoImageMixedPlayerOptimized(Context context, List<String> mediaUrls) {
        this.context = context;
        this.mediaUrls = mediaUrls;
    }

    public void start(PlayerView videoView, ImageView imageView) {
        this.videoView = videoView;
        this.imageView = imageView;
        playNext();
    }

    private void playNext() {
        if (currentIndex >= mediaUrls.size()) currentIndex = 0;

        String url = mediaUrls.get(currentIndex);
        if (isVideo(url)) {
            playVideo(url);
        } else {
            playImage(url);
        }
    }

    private boolean isVideo(String url) {
        return url.endsWith(".mp4") || url.endsWith(".webm");
    }

    @OptIn(markerClass = UnstableApi.class)
    private void playVideo(String url) {
        stopPlayer();

        exoPlayer = new ExoPlayer.Builder(context).build();
        videoView.setPlayer(exoPlayer);
        imageView.setVisibility(ImageView.GONE);
        videoView.setVisibility(PlayerView.VISIBLE);

        MediaItem item = MediaItem.fromUri(Uri.parse(url));
        MediaSource source = new ProgressiveMediaSource.Factory(
                new DefaultDataSource.Factory(context),
                new DefaultExtractorsFactory()
        ).createMediaSource(item);

        exoPlayer.setMediaSource(source);
        exoPlayer.prepare();
        exoPlayer.setPlayWhenReady(true);

        exoPlayer.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int state) {
                if (state == Player.STATE_ENDED) {
                    currentIndex++;
                    playNext();
                }
            }

            @Override
            public void onPlayerError(PlaybackException error) {
                currentIndex++;
                playNext();
            }
        });
    }

    private void playImage(String url) {
        stopPlayer();

        videoView.setVisibility(PlayerView.GONE);
        imageView.setVisibility(ImageView.VISIBLE);

        Glide.with(context)
                .load(url)
                .fitCenter()
                .into(imageView);

        imageHandler = new Handler(Looper.getMainLooper());
        imageHandler.postDelayed(() -> {
            currentIndex++;
            playNext();
        }, 10000);
    }

    private void stopPlayer() {
        if (exoPlayer != null) {
            exoPlayer.release();
            exoPlayer = null;
        }
        if (imageHandler != null) {
            imageHandler.removeCallbacksAndMessages(null);
            imageHandler = null;
        }
    }

    public void stop() {
        stopPlayer();
    }
}

