package com.prank.app.color.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.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.ad.toponlibrary.AdManager;
import com.ad.toponlibrary.onActionListener;
import com.bumptech.glide.Glide;
import com.prank.app.color.R;
import com.prank.app.color.dbdata.DbTool;
import com.prank.app.color.dbdata.MyInfo;
import com.prank.app.color.databinding.ActivityPlayBinding;
import com.prank.app.color.dialog.DialogTimer;
import com.prank.app.color.list.AdapterList;
import com.prank.app.color.api.OnClickListener;
import com.prank.app.color.api.OnSelectTimerListener;
import com.prank.app.color.utils.Common;
import com.prank.app.color.utils.ItemDecoration;

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

public class ActivityPlay extends AppCompatActivity implements View.OnClickListener, OnSelectTimerListener, OnClickListener {

    private ActivityPlayBinding playBinding;

    private MyInfo info;
    private DialogTimer dialogTimer;

    private MediaPlayer mediaPlayer;
    private BroadcastReceiver volumeReceiver;
    private CountDownTimer countDownTimer;

    private boolean isPause = false;
    private int color;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        playBinding = ActivityPlayBinding.inflate(getLayoutInflater());
        setContentView(playBinding.getRoot());
        Common.setStatusBarTextColor(this, true);
        info = (MyInfo) getIntent().getSerializableExtra(Common.KEY_PLAY_DATA);
        color = getIntent().getIntExtra(Common.KEY_LIST_COLOR_POS, 0);
        AdManager.loadAllAd();
        initAudio();
        String covert = info.getCovert();
        if (covert != null && !covert.isEmpty()) {
            Glide.with(this).load(covert)
                    .placeholder(R.drawable.im_def_sounds)
                    .into(playBinding.image);
        } else {
            Glide.with(this).load(R.drawable.im_def_sounds)
                    .into(playBinding.image);
        }
        playBinding.name.setText(info.getName());
        playBinding.back.setOnClickListener(this);
        playBinding.btnPlay.setOnClickListener(this);
        playBinding.imLike.setOnClickListener(this);
        playBinding.imLoop.setOnClickListener(this);
        playBinding.imTimer.setOnClickListener(this);
        Common.setVolume(this, playBinding.seekbar);
        playBinding.linearLayout.setBackground(ContextCompat.getDrawable(this, Common.playBgs[color]));

        initLike();
        loadMore();
        volumeReceiver();
        AdManager.showTopOn(this, new onActionListener() {
            @Override
            public void onAction() {

            }
        });

    }

    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() {
                dialogTimer.setOffSelected();
                if (!mediaPlayer.isPlaying()) {
                    playBinding.btnPlay.setSelected(true);
                    mediaPlayer.start();
                    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() {
        Log.d("---------", "--------info=" + info.isLike());
        boolean b = DbTool.checkLike(info);
        playBinding.imLike.setSelected(b);
    }

    private void loadMore() {
        List<MyInfo> more = DbTool.getMore();
        ItemDecoration itemHelper = new ItemDecoration(0, 0, (int) Common.dpToPx(3));
        AdapterList adapterList = new AdapterList(this, more, 1, this);
        playBinding.moreRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        playBinding.moreRecycler.setAdapter(adapterList);
        playBinding.moreRecycler.addItemDecoration(itemHelper);
        adapterList.setColorIndex(color);
    }

    private void initAudio() {
        showPlayBtn(false);
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(info.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.rippleView.stopRipple();
                    playBinding.btnPlay.setSelected(false);
                    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)) {

            AdManager.showTopOn(ActivityPlay.this, new onActionListener() {
                @Override
                public void onAction() {
                    boolean selected = playBinding.btnPlay.isSelected();
                    if (selected) {
                        if (mediaPlayer.isPlaying()) {
                            playBinding.rippleView.pauseRipple();
                            mediaPlayer.pause();
                            isPause = true;
                        }
                    } else {
                        if (!mediaPlayer.isPlaying()) {
                            mediaPlayer.start();
                            if (isPause) {
                                playBinding.rippleView.resumeRipple();
                            } else {
                                playBinding.rippleView.startRipple();
                            }
                            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) {
                info.setColorIndex(color);
                DbTool.addLike(info);
            } else {
                DbTool.removeLike(info);
            }
        } else if (v.equals(playBinding.imLoop)) {
            playBinding.imLoop.setSelected(!playBinding.imLoop.isSelected());
            mediaPlayer.setLooping(playBinding.imLoop.isSelected());
        } else if (v.equals(playBinding.imTimer)) {
            AdManager.showTopOn(ActivityPlay.this, new onActionListener() {
                @Override
                public void onAction() {
                    if (dialogTimer == null) {
                        dialogTimer = new DialogTimer(ActivityPlay.this, ActivityPlay.this);
                    }
                    dialogTimer.showTop(playBinding.imTimer);
                }
            });

        }

    }

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

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

    }

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