package com.app.sounds.prank.party.act;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.app.sounds.prank.party.R;
import com.app.sounds.prank.party.bean.Info;
import com.app.sounds.prank.party.common.Utils;
import com.app.sounds.prank.party.common.Db;
import com.app.sounds.prank.party.databinding.SaveActivityBinding;
import com.app.sounds.prank.party.top.AdManager;
import com.app.sounds.prank.party.top.onActionListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class SaveActivity extends AppCompatActivity {
    private SaveActivityBinding binding;
    private String path;

    private MediaPlayer mediaPlayer;
    private Handler handler = new Handler();
    private Runnable timeUpdater;
    private long startTime;
    private long elapsedTime;
    private long audioDuration;

    public static String KEY_Time = "KEY_time";
    public static String KEY_Path = "KEY_path";
    public static String KEY_import = "flag";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = SaveActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        AdManager.loadAllAd();
        Utils.setStatusBarTextColor(this, true);
        binding.audioTime.setText(R.string.time_init);
        initData();
        initEvent();


    }

    private void togglePrank() throws IOException {
        if (binding.imPlayBtn.isSelected()) {
            initMediaPlayer();
        } else {
            stopPrank();
        }
    }

    private void stopPrank() {
        handler.removeCallbacks(timeUpdater);
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void initMediaPlayer() {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioAttributes(
                    new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .setUsage(AudioAttributes.USAGE_MEDIA)
                            .build());
            try {
                mediaPlayer.setDataSource(path);
            } catch (Exception ex) {

            }
            mediaPlayer.setOnPreparedListener(mp -> {
                mediaPlayer.start();
                startTimer();
            });
            mediaPlayer.setOnCompletionListener(mp -> {
                binding.imPlayBtn.setSelected(false);
                handler.removeCallbacks(timeUpdater);
            });
            mediaPlayer.prepareAsync();
        } else {
            mediaPlayer.start();
            startTimer();
        }

    }


    private void startTimer() {
        if (timeUpdater == null) {
            timeUpdater = new Runnable() {
                @SuppressLint("DefaultLocale")
                @Override
                public void run() {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        long currentTime = SystemClock.elapsedRealtime();
                        elapsedTime = currentTime - startTime;
                        int milliseconds = (int) (elapsedTime % 1000) / 10;
                        int seconds = (int) (elapsedTime / 1000) % 60;
                        int minutes = (int) (elapsedTime / (1000 * 60)) % 60;
                        binding.audioTime.setText(String.format("%02d : %02d : %02d", minutes, seconds, milliseconds));
                        handler.postDelayed(this, 10);
                    }

                }
            };
        }
        startTime = SystemClock.elapsedRealtime();
        handler.post(timeUpdater);
    }

    private void initEvent() {
        binding.back.setOnClickListener(v -> finish());
        binding.imPlayBtn.setOnClickListener(v -> {
            binding.imPlayBtn.setSelected(!binding.imPlayBtn.isSelected());
            try {
                togglePrank();
            } catch (IOException e) {
                Log.e("SaveActivity", "Error toggling prank", e);
            }
        });
        binding.save.setOnClickListener(v -> {

            AdManager.showTopOn(SaveActivity.this, new onActionListener() {
                @Override
                public void onAction() {

                    String name = binding.saveEdit.getText().toString().trim();
                    boolean b = Db.checkName(name);
                    if (!TextUtils.isEmpty(name)) {
                        if(!b){
                            binding.saveEdit.setText("");
                            Toast.makeText(SaveActivity.this, getString(R.string.name_hint), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        saveData(name);
                        Toast.makeText(SaveActivity.this, getString(R.string.save_tips), Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(SaveActivity.this, getString(R.string.save_tip), Toast.LENGTH_SHORT).show();
                    }

                }
            });

        });
    }

    private void saveData(String name) {
        File cacheDir = getCacheDir();
        File sourceFile = new File(path);
        File destinationFile = new File(cacheDir, name + ".mp3");

        if (sourceFile.renameTo(destinationFile)) {
            Info mydata = new Info();
            mydata.setLike(false);
            mydata.setName(name);
            mydata.setCustomization(true);
            mydata.setAudioUrl(destinationFile.getAbsolutePath());
            Db.getBoxBean().put(mydata);
        } else {
            Log.e("SaveActivity", "Failed to rename file");
        }
    }


    private String readFileFromUri(Context context, Uri uri) {
        ContentResolver contentResolver = context.getContentResolver();
        try (InputStream inputStream = contentResolver.openInputStream(uri);
             FileOutputStream outputStream = new FileOutputStream(new File(getCacheDir(), "temp_audio_file.mp3"))) {

            if (inputStream == null) {
                Log.e("SaveActivity", "Input stream is null");
                return null;
            }
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return new File(getCacheDir(), "temp_audio_file.mp3").getAbsolutePath();
        } catch (IOException e) {
            Log.e("SaveActivity", "Error reading file from URI", e);
            return null;
        }
    }

    private void initData() {
        Intent intent = getIntent();
        audioDuration = intent.getLongExtra(KEY_Time, 0);
        int importFlag = intent.getIntExtra(KEY_import, 0);

        if (importFlag == 1) {
            path = intent.getStringExtra(KEY_Path);
            Log.e("zzj", "save path is" + path);
        } else {
            String uriPath = intent.getStringExtra(KEY_Path);
            Uri uri = Uri.parse(uriPath);
            path = readFileFromUri(this, uri);
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPrank();
    }
}