package com.prank.tool.act;

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 androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.prank.tool.R;
import com.prank.tool.adapter.AdapterChild;
import com.prank.tool.databinding.ActivityLayoutPlayBinding;
import com.prank.tool.interf.OnSoundsListener;
import com.prank.tool.interf.OnTimerListener;
import com.prank.tool.jbean.Info;
import com.prank.tool.popu.PopTimer;
import com.prank.tool.utils.DbManager;
import com.prank.tool.utils.Space;
import com.prank.tool.utils.Tools;

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

public class ActivityPlay extends AppCompatActivity implements View.OnClickListener, OnTimerListener, OnSoundsListener {

    private ActivityLayoutPlayBinding playBinding;

    private Info info;
    private PopTimer popTimer;

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

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

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

        Tools.setVolume(this, playBinding.seekbar);

        initLike();
        loadMore();
        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) {

            }

            @Override
            public void onFinish() {
                popTimer.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 = DbManager.checkLike(info);
        playBinding.imLike.setSelected(b);


    }

    private void loadMore() {
        List<Info> more = DbManager.getMore();
        Space itemHelper = new Space(0, 0, (int) Tools.dpToPx(3));
        AdapterChild adapterChild = new AdapterChild(this, more, 1, this);
        playBinding.moreRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        playBinding.moreRecycler.setAdapter(adapterChild);
        playBinding.moreRecycler.addItemDecoration(itemHelper);
        adapterChild.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.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)) {
            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)) {
            playBinding.imLike.setSelected(!playBinding.imLike.isSelected());
            boolean selected = playBinding.imLike.isSelected();
            if (selected) {
                info.setColorIndex(color);
                DbManager.addLike(info);
            } else {
                DbManager.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)) {
            if (popTimer == null) {
                popTimer = new PopTimer(ActivityPlay.this, this);
            }
            popTimer.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) {
        popTimer.hide();
        if (time == -1) {
            stopCountDown();
        } else {
            startCountDown(time);
        }

    }

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