package com.fun.airhornprank.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 android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
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.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.fun.airhornprank.R;
import com.fun.airhornprank.data.MyDataBase;
import com.fun.airhornprank.data.Mydata;
import com.fun.airhornprank.databinding.ActivityPreViewBinding;
import com.fun.airhornprank.tool.Mytools;
import com.fun.airhornprank.tool.SeekBarBroadCast;
import com.fun.airhornprank.tool.StaticValue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

public class PreViewActivity extends AppCompatActivity {
    ActivityPreViewBinding binding;
    private Mydata data = new Mydata();
    private String title;
    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 = ActivityPreViewBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        EdgeToEdge.enable(this);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_preview), (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_null);
        } else {
            binding.volumeleft.setBackgroundResource(R.drawable.icon_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.preImageLoop.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.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_null);
                } else {
                    binding.volumeleft.setBackgroundResource(R.drawable.icon_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.pre_play);
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void starprank() throws IOException {

        isplayer = true;
        binding.prePlay.setBackgroundResource(R.drawable.pre_pause);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioAttributes(
                new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .build());
        mediaPlayer.setDataSource(data.getMp3Url());
        mediaPlayer.setOnPreparedListener(mp -> {
            if (isloop) {
                mediaPlayer.setLooping(true);
            }
            mediaPlayer.start();
        });
        mediaPlayer.setOnCompletionListener(mp -> {
            if (isloop) {
                binding.prePlay.setBackgroundResource(R.drawable.pre_pause);
            } else {
                binding.prePlay.setBackgroundResource(R.drawable.pre_play);
                isplayer = false;
            }
        });
        mediaPlayer.prepareAsync();
    }

    private void checkLike() {
        if (!islike) {
            islike = true;
            data.setLike(true);
            binding.preLike.setBackgroundResource(R.drawable.icon_like);
            Mytools.runIO(new Runnable() {
                @Override
                public void run() {
                    MyDataBase.getInstance().likeDAO().update(data);
                }
            });

        } else {
            islike = false;
            data.setLike(false);
            binding.preLike.setBackgroundResource(R.drawable.icon_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);
        binding.preText.setText(title);
        Mytools.runIO(new Runnable() {
            @Override
            public void run() {
                List<Mydata> allData = MyDataBase.getInstance().likeDAO().getliketitle(title);
                if (!allData.isEmpty()) {
                    data = allData.get(0);
                    islike = data.getLike();
                    if (islike) {
                        binding.preLike.setBackgroundResource(R.drawable.icon_like);
                    } else {
                        binding.preLike.setBackgroundResource(R.drawable.icon_unlike);
                    }
                    if (data.getPreUrl().equals("custom_url")) {
                        binding.preImage.setImageResource(R.mipmap.save_image);
                    } else {
                        Glide.with(PreViewActivity.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() {

    }

    private void showmenu() {

    }

    @Override
    protected void onStop() {
        super.onStop();
        stopprank();
    }
}