package com.fun.wave.pranksounds.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.fun.wave.pranksounds.R;
import com.fun.wave.pranksounds.base.BaseActivity;
import com.fun.wave.pranksounds.databinding.PlayActivityBinding;
import com.fun.wave.pranksounds.listener.ClickSoundsListener;
import com.fun.wave.pranksounds.listener.ClickTimerListener;
import com.fun.wave.pranksounds.listener.ObjectBoxMan;
import com.fun.wave.pranksounds.listener.PrankBean;
import com.fun.wave.pranksounds.main.ListAdapter;
import com.fun.wave.pranksounds.utils.Common;
import com.fun.wave.pranksounds.utils.ItemDec;
import com.fun.wave.pranksounds.utils.PopupClock;

import java.io.IOException;
import java.util.List;

public class PlayActivity extends BaseActivity<PlayActivityBinding> implements View.OnClickListener, ClickTimerListener, ClickSoundsListener {



    private PrankBean PrankBean;
    private PopupClock popupClock;

    private MediaPlayer mediaPlayer;
    private BroadcastReceiver volumeReceiver;
    private CountDownTimer countDownTimer;
    private int color;
    private boolean isPause = false;



    @Override
    protected void init() {
        PrankBean = (PrankBean) getIntent().getSerializableExtra(Common.KEY_PLAY_DATA);
        color =  getIntent().getIntExtra(Common.KEY_LIST_COLOR_POS,0);
        initAudio();
        String covert = PrankBean.getCovert();
        if (covert != null && !covert.isEmpty()) {
            Glide.with(this).load(covert)
                    .placeholder(R.drawable.image_sounds)
                    .into(viewBind.image);
        } else {
            Glide.with(this).load(R.drawable.image_sounds)
                    .into(viewBind.image);
        }
        viewBind.name.setText(PrankBean.getName());
        viewBind.back.setOnClickListener(this);
        viewBind.btnPlay.setOnClickListener(this);
        viewBind.imLike.setOnClickListener(this);
        viewBind.imLoop.setOnClickListener(this);
        viewBind.imTimer.setOnClickListener(this);
        Common.setVolume(this, viewBind.seekbar);

        initLike();
        loadMore();
        volumeReceiver();
    }

    @Override
    protected PlayActivityBinding initViewBinding() {
        return PlayActivityBinding.inflate(getLayoutInflater());
    }

    private void stopCountDown() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
    private void startCountDown(long time) {
        stopCountDown();
        countDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }
            @Override
            public void onFinish() {
                popupClock.setOffSelected();
                if (!mediaPlayer.isPlaying()) {
                    viewBind.btnPlay.setSelected(true);
                    mediaPlayer.start();
                    isPause = false;
                    viewBind.rippleView.startRipple();
                }
            }
        };
        countDownTimer.start();
    }
    private void volumeReceiver() {
        volumeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) {
                    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                    int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    if (viewBind.seekbar.getProgress() != currentVolume) {
                        viewBind.seekbar.setProgress(currentVolume);
                    }

                }
            }
        };
        IntentFilter filter = new IntentFilter("android.media.VOLUME_CHANGED_ACTION");
        registerReceiver(volumeReceiver, filter);
    }
    private void initLike() {
        boolean b = ObjectBoxMan.checkLike(PrankBean);
        viewBind.imLike.setSelected(b);
    }
    private void loadMore() {
        List<PrankBean> more = ObjectBoxMan.getMore();
        ItemDec itemHelper = new ItemDec(0, 0, (int) Common.dpToPx(3));
        ListAdapter listAdapter = new ListAdapter(this, more, 1, this);
        viewBind.moreRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        viewBind.moreRecycler.setAdapter(listAdapter);
        viewBind.moreRecycler.addItemDecoration(itemHelper);
        listAdapter.setColorIndex(color);
    }

    private void initAudio() {
        showPlayBtn(false);
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(PrankBean.getAudioUrl());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    showPlayBtn(true);
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    viewBind.btnPlay.setSelected(false);
                    viewBind.rippleView.stopRipple();
                    isPause = false;
                }
            });
        } catch (IOException ioException) {
            showPlayBtn(true);
        }
    }

    private void showPlayBtn(boolean showBtn) {
        if (showBtn) {
            viewBind.btnPlay.setVisibility(View.VISIBLE);
            viewBind.playLoading.setVisibility(View.GONE);
        } else {
            viewBind.btnPlay.setVisibility(View.GONE);
            viewBind.playLoading.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View v) {
        if (v.equals(viewBind.back)) {
            finish();
        } else if (v.equals(viewBind.btnPlay)) {
            boolean selected = viewBind.btnPlay.isSelected();
            if (selected) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    viewBind.rippleView.pauseRipple();
                    isPause = true;
                }
            } else {
                if (!mediaPlayer.isPlaying()) {
                    if(isPause){
                        viewBind.rippleView.resumeRipple();
                    }else {
                        viewBind.rippleView.startRipple();
                    }
                    mediaPlayer.start();
                    isPause = false;
                }
            }
            viewBind.btnPlay.setSelected(!selected);

        } else if (v.equals(viewBind.imLike)) {
            viewBind.imLike.setSelected(!viewBind.imLike.isSelected());
            boolean selected = viewBind.imLike.isSelected();
            if (selected) {
                PrankBean.setColorIndex(color);
                ObjectBoxMan.addLike(PrankBean);
            } else {
                ObjectBoxMan.removeLike(PrankBean);
            }
        } else if (v.equals(viewBind.imLoop)) {
            viewBind.imLoop.setSelected(!viewBind.imLoop.isSelected());
            mediaPlayer.setLooping(viewBind.imLoop.isSelected());
        } else if (v.equals(viewBind.imTimer)) {
            if (popupClock == null) {
                popupClock = new PopupClock(PlayActivity.this, this);
            }
            popupClock.showTop(viewBind.imTimer);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        isPause = false;
        mediaPlayer.release();
        mediaPlayer = null;
        stopCountDown();
    }

    @Override
    public void onClickTimerListener(long time) {
        popupClock.hide();
        if (time == -1) {
            stopCountDown();
        } else {
            startCountDown(time);
        }

    }

    @Override
    public void onClickSoundsListener(PrankBean data) {
        Intent intent = new Intent(this, PlayActivity.class);
        intent.putExtra(Common.KEY_PLAY_DATA, data);
        startActivity(intent);
        finish();
    }
}