package com.cartoon.live.wallpaper.ui;

import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.CountDownTimer;
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.source.ProgressiveMediaSource;

import com.cartoon.live.wallpaper.R;
import com.cartoon.live.wallpaper.databinding.ActivityPreviewBinding;
import com.cartoon.live.wallpaper.listener.OnVideoApi;
import com.cartoon.live.wallpaper.mydata.FavoriteData;
import com.cartoon.live.wallpaper.net.ProgressBody;
import com.cartoon.live.wallpaper.net.RetrofitManager;
import com.cartoon.live.wallpaper.parent.BaseActivity;
import com.cartoon.live.wallpaper.utils.Com;
import com.cartoon.live.wallpaper.utils.Db;
import com.cartoon.live.wallpaper.utils.LiveService;
import com.cartoon.live.wallpaper.utils.StoreShared;

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

import io.reactivex.disposables.Disposable;

public class PreviewActivity extends BaseActivity<ActivityPreviewBinding> implements ProgressBody.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 ActivityPreviewBinding getViewBinding() {
        return ActivityPreviewBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void onCreateInit() {
        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 = Com.getCachePath(id);
        mFile = new File(filePath);
        initExoPlay();
        initFavorite();
        if (mFile.exists()) {
            Com.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 OnVideoApi() {
                @Override
                public void onVideoResult(boolean success, String path) {
                    Com.logMsg("-------------success =" + success + "--path=" + path);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (success) {
                                checkPlay();
                            } else {
                                showRetry();
                                Com.logMsg("-------------loading fail");
                            }
                        }
                    });

                }
            });
        } else {
            disposable = RetrofitManager.getInstance().getMp4(id, image, filePath,this, new OnVideoApi() {
                @Override
                public void onVideoResult(boolean success, String path) {
                    Com.logMsg("-------------success =" + success + "--path=" + path);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (success) {
                                checkPlay();
                            } else {
                                showRetry();
                                Com.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);
                    Com.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(PreviewActivity.this, getString(R.string.check_connection), 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) {
                FavoriteData favoriteData = new FavoriteData(describe, id, image, wallpaperType, thumb);
                Db.insertLike(favoriteData);
            } else {
                Db.deleteLike(id);
            }
        } else if (v.equals(vb.layoutSet)) {
            setLiveWallpaper();
        } else if (v.equals(vb.layoutBack)) {
            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()) {
            Com.logMsg("-------------dispose");
            disposable.dispose();
        }


    }

    @OptIn(markerClass = UnstableApi.class)
    private void playMedia3() {
        try {
            Com.logMsg("-------------playMedia3");
            Uri uriFromFilePath = Com.getUriFromFilePath(this, filePath);
            MediaItem mediaItem = MediaItem.fromUri(uriFromFilePath);
            ProgressiveMediaSource mediaSource = createMediaSource(mediaItem);
            exoPlayer.setMediaSource(mediaSource);
            exoPlayer.prepare();
            exoPlayer.play();
        } catch (Exception e) {
            Com.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()) {
            StoreShared.INSTANCE.setVideo_path(filePath);
            Com.logMsg("----------setVideo_path---filePath=" + filePath);
        }

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

        try {
            ComponentName componentName = new ComponentName(PreviewActivity.this, LiveService.class);
            Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
            intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, componentName);
            startActivity(intent);
        } catch (Exception e) {
            Com.logMsg("---------e=" + e.getMessage());
        }
        finish();
    }


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

        if (contentLength <= 0) {
            Com.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);
                            Com.logMsg("------------showLoading------11-----");
                        }else {
                            Com.logMsg("------------showLoading------22-----");
                        }
                        vb.horizontalProgress.setProgress(progress);
                    }
                });
            }

        }
        if (done) {
            Com.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!");
//                }
//            }
//        });

    }
}