package com.fun.originalityprank.activity;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.fun.originalityprank.PrankSkin;
import com.fun.originalityprank.R;
import com.fun.originalityprank.data.AllData;
import com.fun.originalityprank.data.MydataBase;
import com.fun.originalityprank.databinding.ActivityPrewViewBinding;
import com.fun.originalityprank.tool.Mytools;
import com.fun.originalityprank.tool.SeekBarBroadCast;
import com.fun.originalityprank.tool.StaticValue;

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

public class PrewViewActivity extends AppCompatActivity {
    ActivityPrewViewBinding binding;
    private AllData data = new AllData();
    private String title, name;
    private boolean islike = false;
    private boolean isloop = false;
    private boolean isplayer = false;
    private MediaPlayer mediaPlayer;
    private AudioManager audioManager;
    private SeekBarBroadCast seekBarBroadCast;
    private IntentFilter filter = new IntentFilter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPrewViewBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_prew), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        hidemenu();
        initData();
        initEvent();

        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        binding.seekbar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        binding.seekbar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
        if (audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
            binding.volumeleft.setBackgroundResource(R.drawable.icon_volume_null);
        } else {
            binding.volumeleft.setBackgroundResource(R.drawable.icon_volume_left);
        }
        seekBarBroadCast = new SeekBarBroadCast(audioManager, binding.seekbar);

        filter.addAction("android.media.VOLUME_CHANGED_ACTION");
        registerReceiver(seekBarBroadCast, filter);

    }

    private void initEvent() {

        binding.preBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        binding.preLoop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkloop();
            }
        });

        binding.preLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkLike();
            }
        });

        binding.prePlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    playprank();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });


        binding.volumeright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int a = binding.seekbar.getProgress();

                binding.seekbar.setProgress(a + 10);
            }
        });

        binding.volumeleft.setOnClickListener(v -> binding.seekbar.setProgress(0));
        binding.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                if (audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
                    binding.volumeleft.setBackgroundResource(R.drawable.icon_volume_null);
                } else {
                    binding.volumeleft.setBackgroundResource(R.drawable.icon_volume_left);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    private void playprank() throws IOException {
        if (!isplayer) {
            starprank();
        } else {
            stopprank();
        }
    }

    private void stopprank() {
        isplayer = false;
        binding.prePlay.setBackgroundResource(R.drawable.icon_play);
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void starprank() throws IOException {
        isplayer = true;
        binding.prePlay.setBackgroundResource(R.drawable.icon_pause);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioAttributes(
                new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .build());
        mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(data.getMp3Url()));
        mediaPlayer.setOnPreparedListener(mp -> {
            if (isloop) {
                mediaPlayer.setLooping(true);

            }
            mediaPlayer.start();
        });
        mediaPlayer.setOnCompletionListener(mp -> {
            if (isloop) {
                binding.prePlay.setBackgroundResource(R.drawable.icon_pause);
            } else {
                binding.prePlay.setBackgroundResource(R.drawable.icon_play);
                isplayer = true;
            }
        });
        mediaPlayer.prepareAsync();
    }

    private void checkLike() {

        if (!islike) {
            islike = true;
            data.setLike(true);
            binding.preImageLike.setBackgroundResource(R.drawable.icon_pre_like);
            Mytools.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().likeDAO().update(data);
                }
            });

        } else {
            islike = false;
            data.setLike(false);
            binding.preImageLike.setBackgroundResource(R.drawable.icon_pre_unlike);
            Mytools.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().likeDAO().update(data);
                }
            });
        }

    }

    private void checkloop() {

        if (!isloop) {
            isloop = true;
            binding.preImageLoop.setBackgroundResource(R.drawable.icon_loop);
            if (mediaPlayer != null) {
                mediaPlayer.setLooping(true);

            }
        } else {
            isloop = false;
            binding.preImageLoop.setBackgroundResource(R.drawable.icon_unloop);
            if (mediaPlayer != null) {
                mediaPlayer.setLooping(false);

            }
        }

    }

    private void initData() {

        Intent intent = getIntent();
        title = intent.getStringExtra(StaticValue.KEY_TITLE);
        name = intent.getStringExtra(StaticValue.KEY_CategoryName);
        binding.preTitle.setText(name);
        binding.preText.setText(title);
        Mytools.runIO(new Runnable() {
            @Override
            public void run() {
                List<AllData> allData = MydataBase.getInstance().likeDAO().getliketitle(title);
                if (!allData.isEmpty()) {
                    data = allData.get(0);
                    islike = data.getLike();
                    if (islike) {
                        binding.preImageLike.setBackgroundResource(R.drawable.icon_pre_like);
                    } else {
                        binding.preImageLike.setBackgroundResource(R.drawable.icon_pre_unlike);
                    }

                    Glide.with(PrewViewActivity.this)
                            .asBitmap()
                            .load(data.getPreUrl())
                            .placeholder(R.mipmap.logo)
                            .into(new CustomTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    binding.preImage.setImageBitmap(resource);
                                    showmenu();
                                }

                                @Override
                                public void onLoadCleared(@Nullable Drawable placeholder) {

                                }
                            });

                }
            }
        });
    }

    private void hidemenu() {
        binding.preText.setVisibility(View.GONE);
        binding.preLoop.setVisibility(View.GONE);
        binding.preLike.setVisibility(View.GONE);
        binding.volumeleft.setVisibility(View.GONE);
        binding.volumeright.setVisibility(View.GONE);
        binding.seekbar.setVisibility(View.GONE);
        binding.prePlay.setVisibility(View.GONE);
        binding.prePg.setVisibility(View.VISIBLE);
        binding.preImageFrame.setVisibility(View.GONE);
    }

    private void showmenu() {
        binding.preText.setVisibility(View.VISIBLE);
        binding.preLoop.setVisibility(View.VISIBLE);
        binding.preLike.setVisibility(View.VISIBLE);
        binding.volumeleft.setVisibility(View.VISIBLE);
        binding.volumeright.setVisibility(View.VISIBLE);
        binding.seekbar.setVisibility(View.VISIBLE);
        binding.prePlay.setVisibility(View.VISIBLE);
        binding.prePg.setVisibility(View.GONE);
        binding.preImageFrame.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(seekBarBroadCast);
        if (mediaPlayer != null) {
            mediaPlayer.release();
            isplayer = false;
            binding.prePlay.setBackgroundResource(R.drawable.icon_play);
        }
    }
}