package com.atmob.voiceai.module.result;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.SeekBar;

import androidx.annotation.Nullable;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.atmob.app.lib.base.BaseActivity;
import com.atmob.common.logging.AtmobLog;
import com.atmob.voiceai.R;
import com.atmob.voiceai.data.api.bean.UserVoiceBean;
import com.atmob.voiceai.data.api.bean.VoiceListBean;
import com.atmob.voiceai.databinding.ActivityVoiceResultBinding;
import com.atmob.voiceai.module.main.MainActivity;
import com.atmob.voiceai.module.voiceai.VoiceAIFragment;
import com.atmob.voiceai.module.voiceai.VoiceAIListAdapter;
import com.atmob.voiceai.utils.ToastUtil;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class VoiceResultActivity extends BaseActivity<ActivityVoiceResultBinding> {


    private static final String USER_VOICE_BEAN = "user_voice_bean";
    private VoiceResultViewModel voiceResultViewModel;
    private ExoPlayer player;

    private VoiceRecommendAdapter voiceRecommendAdapter;

    public static void start(Context context, UserVoiceBean userVoiceBean) {
        Intent intent = new Intent(context, VoiceResultActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(USER_VOICE_BEAN, userVoiceBean);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        initObserver();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            voiceResultViewModel.setVoiceBean(intent.getParcelableExtra(USER_VOICE_BEAN));
        }
    }

    private void initView() {
        intVoiceRecommendList();
        initMedia3ExoPlayer();
        initSeekBar();
        initPlay();
    }

    private void intVoiceRecommendList() {
        voiceRecommendAdapter = new VoiceRecommendAdapter(this);
        voiceRecommendAdapter.setActionHandler(voiceListBean -> {
            UserVoiceBean value = voiceResultViewModel.getResultBean().getValue();
            if (value == null) {
                return;
            }
            if (player.isPlaying()) {
                player.pause();
                voiceResultViewModel.setVoicePlay(false);
            }
            MainActivity.start(this, VoiceAIFragment.class);
            voiceListBean.setContent(value.getContent());
            voiceResultViewModel.setRecommendVoice(voiceListBean);
            finish();
        });
        binding.rvRecommend.setAdapter(voiceRecommendAdapter);
        binding.rvRecommend.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
    }

    private void initSeekBar() {
        binding.voiceSeekBar.setProgress(0);
        binding.voiceSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                voiceResultViewModel.setCurrentDuration(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                voiceResultViewModel.setSeekbarChanging(true);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                voiceResultViewModel.setSeekbarChanging(false);
                player.seekTo(seekBar.getProgress());
            }
        });
        voiceResultViewModel.startMediaTimer();
    }

    private void initPlay() {
        binding.ivPlay.setOnClickListener(view -> {
            if (player.isLoading()) {
                return;
            }
            if (player.isPlaying()) {
                player.pause();
                voiceResultViewModel.setVoicePlay(false);
            } else {
                player.play();
                voiceResultViewModel.setVoicePlay(true);
            }
        });
        binding.ivVoiceReduce.setOnClickListener(view -> {
            if (player.isLoading()) {
                return;
            }
            player.seekTo(player.getCurrentPosition() - 5000);
        });
        binding.ivVoiceSpeed.setOnClickListener(view -> {
            if (player.isLoading()) {
                return;
            }
            player.seekTo(player.getCurrentPosition() + 5000);
        });
    }

    private void initMedia3ExoPlayer() {
        player = new ExoPlayer.Builder(this).build();
        player.addListener(new Player.Listener() {

            @Override
            public void onPlayerError(PlaybackException error) {
                AtmobLog.d("zk", "onPlayerError: " + error.getMessage());
                ToastUtil.show(R.string.voice_play_error, ToastUtil.LENGTH_SHORT);
                setVoicePlayEnd();
            }

            @Override
            public void onEvents(Player player, Player.Events events) {
                Player.Listener.super.onEvents(player, events);
                if (events.contains(Player.EVENT_IS_LOADING_CHANGED)) {
                    boolean isLoading = player.isLoading();
                    if (!isLoading) {
                        voiceResultViewModel.setTotalDuration(player.getDuration());
                        binding.voiceSeekBar.setMax((int) player.getDuration());
                    }
                }
            }

            @Override
            public void onPlaybackStateChanged(int state) {
                AtmobLog.d("zk", "onPlaybackStateChanged: " + state);
                if (Player.STATE_ENDED == state) {
                    setVoicePlayEnd();
                }
            }

        });
    }

    private void setVoicePlayEnd() {
        player.seekTo(0);
        voiceResultViewModel.setCurrentDuration(0);
        player.pause();
        voiceResultViewModel.setVoicePlay(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
            player.release();
        }
    }

    private void initObserver() {
        voiceResultViewModel.getVoiceList().observe(this, list -> voiceRecommendAdapter.submit(list));
        voiceResultViewModel.getRefreshAudioCurrentProgress().observe(this, o -> {
            long currentPosition = player.getCurrentPosition();
            binding.voiceSeekBar.setProgress((int) currentPosition);
        });
        voiceResultViewModel.getResultBean().observe(this, bean -> {
            if (bean == null) {
                return;
            }
            Uri videoUri = Uri.parse(bean.getVoiceUrl());
            MediaItem mediaItem = MediaItem.fromUri(videoUri);
            player.setMediaItem(mediaItem);
            player.prepare();
            player.setPlayWhenReady(false);
        });
    }

    @Override
    protected boolean shouldImmersion() {
        return true;
    }

    @Override
    protected void initViewModel() {
        super.initViewModel();
        voiceResultViewModel = getViewModelProvider().get(VoiceResultViewModel.class);
        binding.setVoiceResultViewModel(voiceResultViewModel);
    }
}
