package com.fun.funnyprank.activity;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import android.annotation.SuppressLint;
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.view.View;
import android.widget.CompoundButton;
import android.widget.SeekBar;

import com.applovin.mediation.MaxAd;
import com.applovin.mediation.ads.MaxInterstitialAd;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.fun.funnyprank.R;
import com.fun.funnyprank.data.LikeData;
import com.fun.funnyprank.data.MydataBase;
import com.fun.funnyprank.data.StaticValue;
import com.fun.funnyprank.databinding.ActivityPrewBinding;
import com.fun.funnyprank.tools.Adcallback;
import com.fun.funnyprank.tools.Mytools;
import com.fun.funnyprank.tools.SeekBarBroadCast;

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

public class PrewActivity extends AppCompatActivity {
    ActivityPrewBinding binding;
    private String name;
    private AudioManager audioManager;
    private MediaPlayer mediaPlayer;
    private LikeData data;
    private final Boolean[] islike = {false};
    private Boolean isplayer = false;
    private Boolean isloop = false;
    private SeekBar seekBar;
    private static List<MaxInterstitialAd> adsList;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPrewBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

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

        adsList = Mytools.getAllAd();


        initData();
        initEvent();
        hidemenu();
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        seekBar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        seekBar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
        if (audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
            binding.volumeleft.setBackgroundResource(R.drawable.icon_sound_none);
        } else {
            binding.volumeleft.setBackgroundResource(R.drawable.icon_sound_low);
        }
        SeekBarBroadCast seekBarBroadCast = new SeekBarBroadCast(audioManager, seekBar);
        IntentFilter filter = new IntentFilter();
        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.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.loop.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isloop = isChecked;
                if (mediaPlayer != null) {
                    mediaPlayer.setLooping(isloop);
                }
            }
        });
        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_sound_none);
                } else {
                    binding.volumeleft.setBackgroundResource(R.drawable.icon_sound_low);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }
    private void showAd() throws IOException {
        MaxInterstitialAd cachedAd = Mytools.onCache(adsList);

        if (cachedAd == null) {
            starprank();
        } else {
            Mytools.setCallBcak(cachedAd, new Adcallback() {
                @Override
                public void onShowFail(MaxAd ad) {
                    try {
                        starprank();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void onAdHidden() {
                    try {
                        starprank();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            cachedAd.showAd(this);
        }
    }
    private void playprank() throws IOException {
        if (!isplayer) {
           showAd();
        } 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[0]) {
            binding.preLike.setBackgroundResource(R.drawable.icon_liek_check);
            islike[0] = true;
            data.setLike(true);
            Mytools.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().likeDao().update(data);
                }
            });
        } else {
            binding.preLike.setBackgroundResource(R.drawable.icon_liek_uncheck);
            islike[0] = false;
            data.setLike(false);
            Mytools.runIO(new Runnable() {
                @Override
                public void run() {
                    MydataBase.getInstance().likeDao().update(data);
                }
            });
        }
    }

    private void initData() {
        seekBar = findViewById(R.id.seekbar);
        Intent intent = getIntent();
        name = intent.getStringExtra(StaticValue.KEY_TITLE);
        Mytools.runIO(new Runnable() {
            @Override
            public void run() {
                List<LikeData> existingData = MydataBase.getInstance().likeDao().getliketitle(name);
                if (!existingData.isEmpty()) {
                    data = existingData.get(0);
                    islike[0] = data.getLike();
                    if (islike[0]) {
                        binding.preLike.setBackgroundResource(R.drawable.icon_liek_check);
                    } else {
                        binding.preLike.setBackgroundResource(R.drawable.icon_liek_uncheck);
                    }
                    binding.preTitle.setText(data.getTitle());
                    if (name.equals("custom_url")){
                        binding.preImage.setBackgroundResource(R.mipmap.save_image);
                    }else {
                        Glide.with(PrewActivity.this)
                                .asBitmap()
                                .load(data.getPreUrl())
                                .placeholder(R.mipmap.icon_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.loop.setVisibility(View.GONE);
        binding.preLoopText.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.preCons.setVisibility(View.GONE);
    }

    private void showmenu() {
        binding.loop.setVisibility(View.VISIBLE);
        binding.preLoopText.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.preCons.setVisibility(View.VISIBLE);
    }

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