package com.light.prank.sound.app.allui;

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.Bundle;
import android.os.CountDownTimer;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.light.prank.sound.app.utils.MyItemSpace;
import com.light.prank.sound.app.utils.MyUtils;
import com.light.prank.sound.app.dataListener.objectBoxMan;
import com.light.prank.sound.app.dataListener.OnClickItemListener;
import com.light.prank.sound.app.dataListener.OnClickTimerListener;
import com.light.prank.sound.app.dataListener.PrankBean;
import com.prank.tool.sounds.app.R;
import com.prank.tool.sounds.app.databinding.AcPlayPranksBinding;

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

public class AcPlayPranks extends AppCompatActivity implements View.OnClickListener, OnClickTimerListener, OnClickItemListener {

    private AcPlayPranksBinding playBinding;

    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 onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        playBinding = AcPlayPranksBinding.inflate(getLayoutInflater());
        setContentView(playBinding.getRoot());
        MyUtils.setStatusBarTextColor(this, true);
        PrankBean = (PrankBean) getIntent().getSerializableExtra(MyUtils.KEY_PLAY_DATA);
        color =  getIntent().getIntExtra(MyUtils.KEY_LIST_COLOR_POS,0);
//        playBinding.constraintLayout.setBackground(ContextCompat.getDrawable(this, Tools.playBgs[color]));
        initAudio();
        String covert = PrankBean.getCovert();
        if (covert != null && !covert.isEmpty()) {
            Glide.with(this).load(covert)
                    .placeholder(R.drawable.drawable_sounds)
                    .into(playBinding.image);
        } else {
            Glide.with(this).load(R.drawable.drawable_sounds)
                    .into(playBinding.image);
        }
        playBinding.name.setText(PrankBean.getName());
        playBinding.back.setOnClickListener(this);
        playBinding.btnPlay.setOnClickListener(this);
        playBinding.imLike.setOnClickListener(this);
        playBinding.imLoop.setOnClickListener(this);
        playBinding.imTimer.setOnClickListener(this);
        MyUtils.setVolume(this, playBinding.seekbar);

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

    }

    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()) {
                    playBinding.btnPlay.setSelected(true);
                    mediaPlayer.start();
                    isPause = false;
                    playBinding.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 (playBinding.seekbar.getProgress() != currentVolume) {
                        playBinding.seekbar.setProgress(currentVolume);
                    }

                }
            }
        };
        IntentFilter filter = new IntentFilter("android.media.VOLUME_CHANGED_ACTION");
        registerReceiver(volumeReceiver, filter);
    }
    private void initLike() {
        boolean b = objectBoxMan.checkLike(PrankBean);
        playBinding.imLike.setSelected(b);
    }
    private void loadMore() {
        List<PrankBean> more = objectBoxMan.getMore();
        MyItemSpace itemHelper = new MyItemSpace(0, 0, (int) MyUtils.dpToPx(3));
        AdapterCategoryList adapterCategoryList = new AdapterCategoryList(this, more, 1, this);
        playBinding.moreRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        playBinding.moreRecycler.setAdapter(adapterCategoryList);
        playBinding.moreRecycler.addItemDecoration(itemHelper);
        adapterCategoryList.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) {
                    playBinding.btnPlay.setSelected(false);
                    playBinding.rippleView.stopRipple();
                    isPause = false;
                }
            });
        } catch (IOException ioException) {
            showPlayBtn(true);
        }
    }

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


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

        } else if (v.equals(playBinding.imLike)) {
            playBinding.imLike.setSelected(!playBinding.imLike.isSelected());
            boolean selected = playBinding.imLike.isSelected();
            if (selected) {
                PrankBean.setColorIndex(color);
                objectBoxMan.addLike(PrankBean);
            } else {
                objectBoxMan.removeLike(PrankBean);
            }
        } else if (v.equals(playBinding.imLoop)) {
            playBinding.imLoop.setSelected(!playBinding.imLoop.isSelected());
            mediaPlayer.setLooping(playBinding.imLoop.isSelected());
        } else if (v.equals(playBinding.imTimer)) {
            if (popupClock == null) {
                popupClock = new PopupClock(AcPlayPranks.this, this);
            }
            popupClock.showTop(playBinding.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, AcPlayPranks.class);
        intent.putExtra(MyUtils.KEY_PLAY_DATA, data);
        startActivity(intent);
        finish();
    }
}