package com.live.mylivewallpaper.activity;

import android.app.WallpaperManager;
import android.content.ActivityNotFoundException;
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 android.widget.Toast;

import androidx.annotation.OptIn;
import androidx.media3.common.MediaItem;
import androidx.media3.common.Player;
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.R;
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.ProgressResponseBody;
import com.live.mylivewallpaper.request.RetrofitManager;
import com.live.mylivewallpaper.topon.AdManager;
import com.live.mylivewallpaper.topon.onActionListener;

import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;

import io.reactivex.disposables.Disposable;

public class VideoActivity extends BaseActivity<ActivityVideoBinding> implements ProgressResponseBody.ProgressListener {


    private CountDownTimer countDownTimer;


    private String filePath;
    private File mFile;

//    private boolean download = false;

    private ExoPlayer 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";

    //    private boolean loadingui = false;
    private  AtomicBoolean loadingui ;
    private Disposable disposable;

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

    @Override
    protected void onCreateInit() {
        AdManager.loadAllAd();
        showLoading(true, false);
        Intent intent = getIntent();
        id = intent.getIntExtra(KEY_ID, -1);
        wallpaperType = intent.getIntExtra(KEY_wallpaperType, -1);
        image = intent.getStringExtra(KEY_image);
        describe = intent.getStringExtra(KEY_describe);
        thumb = intent.getStringExtra(KEY_thumb);
        vb.tvDescribe.setText(describe);
        filePath = Common.getCachePath(id);
        mFile = new File(filePath);
        initExoPlay();
        initFavorite();
        if (mFile.exists()) {
            Common.logMsg("------checkPlay-");
            checkPlay();
            return;
        }
        loadingui = new AtomicBoolean(false);
        requestVideo();


    }

    private void requestVideo() {

        if (wallpaperType == 2) {
            //shift
            disposable = RetrofitManager.getInstance().getShiftMp4(id, image, filePath,this, new OnVideoResultListener() {
                @Override
                public void onVideoResult(boolean success, String path) {
                    Common.logMsg("-------------success =" + success + "--path=" + path);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (success) {
                                checkPlay();
                            } else {
                                showRetry();
                                Common.logMsg("-------------loading fail");
                            }
                        }
                    });

                }
            });
        } else {
            disposable = RetrofitManager.getInstance().getMp4(id, image, filePath,this, new OnVideoResultListener() {
                @Override
                public void onVideoResult(boolean success, String path) {
                    Common.logMsg("-------------success =" + success + "--path=" + path);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (success) {
                                checkPlay();
                            } else {
                                // TODO: 2024/12/23 下载失败
                                showRetry();
                                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 ExoPlayer.Builder(this)
                .build();
        exoPlayer.setRepeatMode(ExoPlayer.REPEAT_MODE_ONE);
        vb.playerView.setPlayer(exoPlayer);
        exoPlayer.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int playbackState) {
                if (playbackState == Player.STATE_READY) {
                    showLoading(false, true);
                    Common.logMsg("-------onPlaybackStateChanged-----" + exoPlayer.getPlayWhenReady());
                }
            }
        });
    }

    private void checkPlay() {
        playMedia3();
    }

    private void showLoading(boolean loading, boolean isHorizontal) {
        if (loading) {
            vb.layoutRetry.setVisibility(View.GONE);
            vb.relativeLoading.setVisibility(View.VISIBLE);
            if (isHorizontal) {
                vb.horizontalLayout.setVisibility(View.VISIBLE);
                vb.normalProgress.setVisibility(View.GONE);
            } else {
                vb.normalProgress.setVisibility(View.VISIBLE);
                vb.horizontalLayout.setVisibility(View.GONE);
            }
        } else {
            if (isHorizontal) {
                vb.horizontalProgress.setProgress(100);
            }
            vb.relativeLoading.setVisibility(View.GONE);
        }

    }

    private void showRetry() {
        Toast.makeText(VideoActivity.this, getString(R.string.check_net), Toast.LENGTH_SHORT).show();
        vb.relativeLoading.setVisibility(View.VISIBLE);
        vb.horizontalLayout.setVisibility(View.GONE);
        vb.normalProgress.setVisibility(View.GONE);
        vb.layoutRetry.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onInitClick() {
        vb.layoutFavorite.setOnClickListener(this);
        vb.layoutSet.setOnClickListener(this);
        vb.layoutBack.setOnClickListener(this);
        vb.tvRetry.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)) {
           AdManager.showTopOn(VideoActivity.this, new onActionListener() {
               @Override
               public void onAction() {
                   setLiveWallpaper();
               }
           });
        } else if (v.equals(vb.layoutBack)) {
            AdManager.showTopOn(VideoActivity.this, new onActionListener() {
                @Override
                public void onAction() {
                    finish();
                }
            });
        } else if (v.equals(vb.tvRetry)) {
            requestVideo();
        }


    }

    @OptIn(markerClass = UnstableApi.class)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (exoPlayer != null) {
            exoPlayer.release();
        }

        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        if (disposable != null && !disposable.isDisposed()) {
            Common.logMsg("-------------dispose");
            disposable.dispose();
        }


    }

    @OptIn(markerClass = UnstableApi.class)
    private void playMedia3() {
        try {
            Common.logMsg("-------------playMedia3");
            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());
        }

        try {
            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);
        } catch (Exception e) {
            Common.logMsg("---------e=" + e.getMessage());
        }
        finish();
    }


    @Override
    public void onProgress(long bytesRead, long contentLength, boolean done) {

        if (contentLength <= 0) {
            Common.logMsg("contentLength" + contentLength);
        } else {
            int progress = (int) ((100 * bytesRead) / contentLength);
//            Common.logMsg("Download progress: " + progress + "%"+"---loadingui="+loadingui);
            if (vb.horizontalProgress.getProgress() != progress) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(vb.horizontalLayout.getVisibility() != View.VISIBLE){
                            showLoading(true, true);
                            Common.logMsg("------------showLoading------11-----");
                        }else {
                            Common.logMsg("------------showLoading------22-----");
                        }
                        vb.horizontalProgress.setProgress(progress);
                    }
                });
            }

        }
        if (done) {
            Common.logMsg("Download complete!");
        }


//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (contentLength <= 0) {
//                    Common.logMsg("contentLength" +contentLength);
//                } else {
//                    showLoading(true, true);
//                    int progress = (int) ((100 * bytesRead) / contentLength);
//                    Common.logMsg("Download progress: " + progress + "%"+"---loadingui="+loadingui);
//                    vb.horizontalProgress.setProgress(progress);
//                }
//                if (done) {
//                    Common.logMsg("Download complete!");
//                }
//            }
//        });

    }
}