package com.live.mylivewallpaper.activity;

import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.CountDownTimer;
import android.view.SurfaceHolder;
import android.view.View;

import androidx.annotation.OptIn;
import androidx.media3.common.MediaItem;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.datasource.DefaultDataSourceFactory;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.SimpleExoPlayer;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;

import com.live.mylivewallpaper.base.BaseActivity;
import com.live.mylivewallpaper.data.LikeData;
import com.live.mylivewallpaper.databinding.ActivityVideoBinding;
import com.live.mylivewallpaper.help.Common;
import com.live.mylivewallpaper.help.Db;
import com.live.mylivewallpaper.help.LiveWallpaperService;
import com.live.mylivewallpaper.help.Shared;
import com.live.mylivewallpaper.listener.OnVideoResultListener;
import com.live.mylivewallpaper.request.RetrofitManager;

import java.io.File;

public class VideoActivity extends BaseActivity<ActivityVideoBinding>  {


    private CountDownTimer countDownTimer;

    private long time = 5000;

    private SurfaceHolder mySurfaceHolder;
    private String filePath;
    private File mFile;

    private boolean download = false;

    private SimpleExoPlayer exoPlayer;


    private int id;
    private String image;
    private String describe;
    private String thumb;
    private int wallpaperType;

    public static String KEY_ID = "ID";
    public static String KEY_image = "image";
    public static String KEY_describe = "describe";
    public static String KEY_wallpaperType = "wallpaperType";
    public static String KEY_thumb = "thumb";

    @Override
    protected ActivityVideoBinding getViewBinding() {
        return ActivityVideoBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void onCreateInit() {
        Intent intent = getIntent();
        id = intent.getIntExtra(KEY_ID, -1);
        wallpaperType = intent.getIntExtra(KEY_wallpaperType, -1);
        image = intent.getStringExtra(KEY_image);
        describe = intent.getStringExtra(KEY_image);
        thumb = intent.getStringExtra(KEY_thumb);
        vb.tvDescribe.setText(describe);

        showLoading(true);
        initFavorite();
        filePath = Common.getCachePath(id);
        mFile = new File(filePath);
        initExoPlay();

        if (mFile.exists()) {
            showLoading(false);
            download = true;
            checkPlay();
            return;
        }
        RetrofitManager.getInstance().getMp4(id, image, filePath, new OnVideoResultListener() {
            @Override
            public void onVideoResult(boolean success, String path) {

                Common.logMsg("-------------success =" + success + "--path=" + path);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showLoading(false);
                        if (success) {
                            download = true;
                            checkPlay();
                        } else {
                            Common.logMsg("-------------loading fail");
                        }
                    }
                });

            }
        });

    }

    private void initFavorite() {
        boolean b = Db.queryIsLike(id);
        vb.imFavorite.setSelected(b);
    }

    @OptIn(markerClass = UnstableApi.class)
    private void initExoPlay() {
        exoPlayer = new SimpleExoPlayer.Builder(this)
                .build();
        exoPlayer.setRepeatMode(ExoPlayer.REPEAT_MODE_ONE);
        vb.playerView.setPlayer(exoPlayer);
    }


    private void checkPlay() {

        if (download) {
            playMedia3();
        }
    }




    private void showLoading(boolean loading) {
        if (loading) {
//            vb.topLayout.setBackgroundColor(getColor(R.color.color_white_80));
            vb.relativeLoading.setVisibility(View.VISIBLE);
            countDownTimer = new CountDownTimer(time, 100L) {
                @Override
                public void onTick(long millisUntilFinished) {
                    float v = 100 - (float) millisUntilFinished / time * 100;
                    int v1 = (int) v;
                    vb.progress.setProgress(v1);
                }

                @Override
                public void onFinish() {

                }
            };
            countDownTimer.start();
        } else {
            vb.progress.setProgress(100);
//            vb.topLayout.setBackgroundColor(getColor(R.color.transparent));
            vb.relativeLoading.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onInitClick() {
        vb.layoutFavorite.setOnClickListener(this);
        vb.layoutSet.setOnClickListener(this);
        vb.layoutBack.setOnClickListener(this);
    }

    @Override
    public boolean isFullScreen() {
        return true;
    }

    @Override
    public boolean statusBarLight() {
        return true;
    }

    @Override
    public void onClick(View v) {
        if (v.equals(vb.layoutFavorite)) {
            vb.imFavorite.setSelected(!vb.imFavorite.isSelected());
            boolean selected = vb.imFavorite.isSelected();
            if (selected) {
                LikeData likeData = new LikeData(describe, id, image, wallpaperType, thumb);
                Db.insertLike(likeData);
            } else {
                Db.deleteLike(id);
            }
        } else if (v.equals(vb.layoutSet)) {
            setLiveWallpaper();
        } else if (v.equals(vb.layoutBack)) {
            finish();
        }


    }

    @OptIn(markerClass = UnstableApi.class)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (exoPlayer != null) {
            exoPlayer.release();
        }
        Common.logMsg("-----Video-------onDestroy");
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }


    }

    @OptIn(markerClass = UnstableApi.class)
    private void playMedia3() {
        try {
            Uri uriFromFilePath = Common.getUriFromFilePath(this, filePath);
            MediaItem mediaItem = MediaItem.fromUri(uriFromFilePath);
            ProgressiveMediaSource mediaSource = createMediaSource(mediaItem);
            exoPlayer.setMediaSource(mediaSource);
            exoPlayer.prepare();
            exoPlayer.play();
        } catch (Exception e) {
            Common.logMsg("-------" + e.getMessage());
        }
    }

    @OptIn(markerClass = UnstableApi.class)
    public ProgressiveMediaSource createMediaSource(MediaItem mediaItem) {
        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(
                this, "user-agent"
        );
        ProgressiveMediaSource.Factory factory = new ProgressiveMediaSource.Factory(dataSourceFactory);
        return factory.createMediaSource(mediaItem);
    }


    private void setLiveWallpaper() {
        if (mFile.exists()) {
            Shared.INSTANCE.setVideo_path(filePath);
            Common.logMsg("----------setVideo_path---filePath=" + filePath);
        }

        WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
        try {
            wallpaperManager.clear();
            Common.logMsg("----------clear=");
        } catch (Exception e) {
            Common.logMsg("---------e=" + e.getMessage());
        }

        ComponentName componentName = new ComponentName(VideoActivity.this, LiveWallpaperService.class);
        Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
        intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, componentName);
        startActivity(intent);
        finish();
    }


}