package com.hd.live.wall.wallpapers.act;

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.PlaybackException;
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.hd.live.wall.wallpapers.R;
import com.hd.live.wall.wallpapers.base.BasisActivity;
import com.hd.live.wall.wallpapers.databinding.ActivitySetWallpapersBinding;
import com.hd.live.wall.wallpapers.dbData.Collection;
import com.hd.live.wall.wallpapers.listener.ListenerResult;
import com.hd.live.wall.wallpapers.retrofitman.ResBody;
import com.hd.live.wall.wallpapers.retrofitman.DataRequest;
import com.hd.live.wall.wallpapers.utils.helper;
import com.hd.live.wall.wallpapers.utils.LiveService;
import com.hd.live.wall.wallpapers.utils.dbManager;
import com.hd.live.wall.wallpapers.utils.Store;

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

import io.reactivex.disposables.Disposable;

public class ActivitySetWallpaper extends BasisActivity<ActivitySetWallpapersBinding> implements ResBody.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;
    private String netFail, fileFail;
    @Override
    protected ActivitySetWallpapersBinding getViewBinding() {
        return ActivitySetWallpapersBinding.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 = helper.getCachePath(id);
        mFile = new File(filePath);
        initExoPlay();
        initFavorite();
        fileFail = getString(R.string.loading_fail);
        netFail =  getString(R.string.check_connection);
        if (mFile.exists()) {
            helper.logMsg("------checkPlay-");
            checkPlay();
            return;
        }
        loadingui = new AtomicBoolean(false);
        requestVideo();


    }

    private void requestVideo() {

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

                }
            });
        } else {
            disposable = DataRequest.getInstance().getMp4(id, image, filePath,this, new ListenerResult() {
                @Override
                public void onVideoResult(boolean success, String path) {
                    helper.logMsg("-------------success =" + success + "--path=" + path);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (success) {
                                checkPlay();
                            } else {
                                showRetry(netFail);
                                helper.logMsg("-------------loading fail");
                            }
                        }
                    });

                }
            });
        }
    }

    private void initFavorite() {
        boolean b = dbManager.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);
                    helper.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(String msg) {
        Toast.makeText(ActivitySetWallpaper.this, msg, 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.like.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 false;
    }

    @Override
    public void onClick(View v) {
        if (v.equals(vb.like)) {
            vb.imFavorite.setSelected(!vb.imFavorite.isSelected());
            boolean selected = vb.imFavorite.isSelected();
            if (selected) {
                Collection collection = new Collection(describe, id, image, wallpaperType, thumb);
                dbManager.insertLike(collection);
            } else {
                dbManager.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()) {
            helper.logMsg("-------------dispose");
            disposable.dispose();
        }


    }

    @OptIn(markerClass = UnstableApi.class)
    private void playMedia3() {
        try {
            helper.logMsg("-------------playMedia3");
            Uri uriFromFilePath = helper.getUriFromFilePath(this, filePath);
            MediaItem mediaItem = MediaItem.fromUri(uriFromFilePath);
            ProgressiveMediaSource mediaSource = createMediaSource(mediaItem);
            exoPlayer.setMediaSource(mediaSource);
            exoPlayer.addListener(new Player.Listener() {
                @Override
                public void onPlayerError(PlaybackException error) {
                    helper.logMsg("-------------onPlayerError");
                    helper.deleteFile(mFile);
                    showRetry(fileFail);
                }
            });
            exoPlayer.prepare();
            exoPlayer.play();
        } catch (Exception e) {
            helper.logMsg("-------" + e.getMessage());
            helper.deleteFile(mFile);
            showRetry(fileFail);
        }
    }

    @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()) {
            Store.INSTANCE.setVideo_path(filePath);
            helper.logMsg("----------setVideo_path---filePath=" + filePath);
        }

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

        try {
            ComponentName componentName = new ComponentName(ActivitySetWallpaper.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) {
            helper.logMsg("---------e=" + e.getMessage());
        }
        finish();
    }


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

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

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




    }
}