package com.prankster.fx.ui.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 android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.gyf.immersionbar.ImmersionBar;
import com.prankster.fx.R;
import com.prankster.fx.databinding.ActivityPlayBinding;
import com.prankster.fx.db.Bean;
import com.prankster.fx.db.ObManager;
import com.prankster.fx.topon.AdManager;
import com.prankster.fx.topon.onActionListener;
import com.prankster.fx.utils.CommonUtils;
import com.prankster.fx.utils.ConstValues;
import com.prankster.fx.utils.OnClickTimer;
import com.prankster.fx.ui.view.TimerDialog;

import java.io.IOException;

public class FXPlayAct extends AppCompatActivity implements View.OnClickListener, OnClickTimer {

    private ActivityPlayBinding playBinding;

    private Bean bean;
    private TimerDialog timerDialog;

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

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

        playBinding = ActivityPlayBinding.inflate(getLayoutInflater());
        setContentView(playBinding.getRoot());
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .statusBarView(playBinding.view)
                .init();
        bean = (Bean) getIntent().getSerializableExtra(ConstValues.KEY_PLAY_DATA);
        AdManager.loadAllAd();
        AdManager.showTopOn(this, new onActionListener() {
            @Override
            public void onAction() {

            }
        });
        initAudio();
        String covert = bean.getCovert();
        if (covert != null && !covert.isEmpty()) {
            Glide.with(this).load(covert)
                    .placeholder(R.drawable.tab_home_no)
                    .into(playBinding.image);
        } else {
            Glide.with(this).load(R.drawable.import_audio)
                    .placeholder(R.drawable.tab_home_no)
                    .into(playBinding.image);
        }
        playBinding.name.setText(bean.getName());
        playBinding.back.setOnClickListener(this);
        playBinding.linearPlay.setOnClickListener(this);
        playBinding.imLike.setOnClickListener(this);
        playBinding.imLoop.setOnClickListener(this);
        playBinding.imTimer.setOnClickListener(this);

        CommonUtils.setVolume(this, playBinding.seekbar);

        initLike();
        volumeReceiver();

    }

    private void stopCountDown() {
        Log.d("------", "------stopCountDown");
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    private void startCountDown(long time) {
        stopCountDown();
        countDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.d("------", "------millisUntilFinished=" + millisUntilFinished);
            }

            @Override
            public void onFinish() {
                Log.d("------", "------onFinish");
                timerDialog.setOffSelected();
                if (!mediaPlayer.isPlaying()) {
                    playBinding.btnPlay.setSelected(true);
                    mediaPlayer.start();
                }
            }
        };
        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 = ObManager.checkLike(bean);
        playBinding.imLike.setSelected(b);


    }

    private void initAudio() {
        showPlayBtn(false);
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(bean.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);
                }
            });
        } catch (IOException ioException) {
            showPlayBtn(true);
            Toast.makeText(this, "----------prepare fail", Toast.LENGTH_SHORT).show();
        }
    }

    private void showPlayBtn(boolean showBtn) {
        if (showBtn) {
            playBinding.linearPlay.setVisibility(View.VISIBLE);
            playBinding.playLoading.setVisibility(View.GONE);
        } else {
            playBinding.linearPlay.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.linearPlay)) {

            AdManager.showTopOn(FXPlayAct.this, new onActionListener() {
                @Override
                public void onAction() {
                    boolean selected = playBinding.btnPlay.isSelected();
                    if (selected) {
                        if (mediaPlayer.isPlaying()) {
                            mediaPlayer.pause();
                        }
                    } else {
                        if (!mediaPlayer.isPlaying()) {
                            mediaPlayer.start();
                        }
                    }
                    playBinding.btnPlay.setSelected(!selected);
                }
            });


        } else if (v.equals(playBinding.imLike)) {
            AdManager.showTopOn(FXPlayAct.this, new onActionListener() {
                @Override
                public void onAction() {
                    playBinding.imLike.setSelected(!playBinding.imLike.isSelected());
                    boolean selected = playBinding.imLike.isSelected();
                    if (selected) {
                        ObManager.addLike(bean);
                    } else {
                        ObManager.removeLike(bean);
                    }
                }
            });

        } else if (v.equals(playBinding.imLoop)) {
            playBinding.imLoop.setSelected(!playBinding.imLoop.isSelected());
            mediaPlayer.setLooping(playBinding.imLoop.isSelected());
        } else if (v.equals(playBinding.imTimer)) {
            if (timerDialog == null) {
                timerDialog = new TimerDialog(FXPlayAct.this, this);
            }
            timerDialog.showTop(playBinding.imTimer);
        }

    }

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

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

    }
}