package es.uniovi.pruebacsep2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

    private TextView tFC;
    private RadioGroup RG1;
    private RadioGroup RG2;
    private RadioButton RB1;
    private RadioButton RB2;
    private RadioButton RB3;
    private RadioButton RB4;
    private RadioButton RB5;
    private RadioButton RB6;
    private RadioButton RB7;
    private RadioButton RB8;


    private ImageButton b1,b2,b3,b4;
    private Button bProcesar;
    private ImageView iv;
    private MediaPlayer mediaPlayer;

    private double startTime = 0;
    private double finalTime = 0;

    private Handler myHandler = new Handler();;
    private int forwardTime = 1000;
    private int backwardTime = 1000;
    private SeekBar seekbar;
    private TextView tx1,tx2,tx3;

    private boolean pausado=false;

    public static int oneTimeOnly = 0;


    static {
        System.loadLibrary("CardioPulmon");
    }

    private static AssetManager mgr;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tFC = findViewById(R.id.tFC);
        RG1=(RadioGroup) findViewById(R.id.RG1);
        RG2=(RadioGroup) findViewById(R.id.RG2);
        RB1=(RadioButton) findViewById(R.id.RB1);
        RB2=(RadioButton) findViewById(R.id.RB2);
        RB3=(RadioButton) findViewById(R.id.RB3);
        RB4=(RadioButton) findViewById(R.id.RB4);
        RB5=(RadioButton) findViewById(R.id.RB5);
        RB6=(RadioButton) findViewById(R.id.RB6);
        RB7=(RadioButton) findViewById(R.id.RB7);
        RB8=(RadioButton) findViewById(R.id.RB8);

        b1 = (ImageButton) findViewById(R.id.b1);
        b2 = (ImageButton) findViewById(R.id.b2);
        b3 = (ImageButton)findViewById(R.id.b3);
        b4 = (ImageButton)findViewById(R.id.b4);
        bProcesar = (Button)findViewById(R.id.bProcesar);

        tx1 = (TextView)findViewById(R.id.tx1);
        tx2 = (TextView)findViewById(R.id.tx2);

        seekbar = (SeekBar)findViewById(R.id.seekBar);
        seekbar.setClickable(true);
        b2.setEnabled(false);


        Context mContext=this;

        int REQUEST = 112;

        if (Build.VERSION.SDK_INT >= 23) {
            String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (!hasPermissions(mContext, PERMISSIONS)) {
                ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
            } else {
                //do here
            }
        } else {
            //do here
        }


        mgr = getResources().getAssets();

        b1.setEnabled(false);
        b2.setEnabled(false);
        b3.setEnabled(false);
        b4.setEnabled(false);

    }

    public void onClickProcesar(View view){

        String archivo;
        String salida;
        seekbar.setClickable(true);

        if(RB1.isChecked()){
            archivo="mezcla007segundos.wav";
        }
        else if (RB2.isChecked()){
            archivo="mezcla014segundos.wav";
        }
        else if (RB3.isChecked()){
            archivo="mezcla028segundos.wav";
        }
        else if (RB6.isChecked()){
            archivo="mezcla042segundos.wav";
        }
        else if (RB7.isChecked()){
            archivo="mezcla056segundos.wav";
        }
        else{
            archivo="mezcla070segundos.wav";
        }


        if(RB4.isChecked()){
            salida="/Corazon.wav";
        }
        else{
            salida="/Pulmon.wav";
        }


        double fc=total(mgr,archivo,getFilesDir().toString());


        mediaPlayer = MediaPlayer.create(this, Uri.parse(getFilesDir()+salida));
        mediaPlayer.start();
        pausado=false;
        String frec=String.format("%.0f", fc);
        tFC.setText("FC: "+frec+"ppm");

        finalTime = mediaPlayer.getDuration();
        startTime = mediaPlayer.getCurrentPosition();


        seekbar.setMax((int) finalTime);
        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
                // TODO Auto-generated method stub
                if(!pausado) {
                    if (!mediaPlayer.isPlaying()) {
                        mediaPlayer.start();
                        mediaPlayer.seekTo(progress);
                    }
                    if (fromUser) {
                        mediaPlayer.seekTo(progress);
                    }
                }
            }
        });



        tx2.setText(String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
                TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
                                finalTime)))
        );

        tx1.setText(String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
                                startTime)))
        );

        seekbar.setProgress((int)startTime);

        myHandler.postDelayed(UpdateSongTime,100);
        b1.setEnabled(true);
        b2.setEnabled(true);
        b3.setEnabled(false);
        b4.setEnabled(true);



    }

    public void onClickPlay(View view){
        mediaPlayer.start();

        finalTime = mediaPlayer.getDuration();
        startTime = mediaPlayer.getCurrentPosition();

        if (oneTimeOnly == 0) {
            seekbar.setMax((int) finalTime);
            oneTimeOnly = 1;
        }

        tx2.setText(String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
                TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
                                finalTime)))
        );

        tx1.setText(String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long)
                                startTime)))
        );

        seekbar.setProgress((int)startTime);

        myHandler.postDelayed(UpdateSongTime,100);
        b2.setEnabled(true);
        b3.setEnabled(false);
        pausado=false;
    }

    public void onClickPause(View view){
        mediaPlayer.pause();
        b2.setEnabled(false);
        b3.setEnabled(true);
        pausado=true;
    }

    public void onClickAvanzar(View view){
        int temp = (int)startTime;

        if((temp+forwardTime)<=finalTime){
            startTime = startTime + forwardTime;
            mediaPlayer.seekTo((int) startTime);
        }else{
        }
    }


    public void onClickAtras(View view){
        int temp = (int)startTime;

        if((temp-backwardTime)>0){
            startTime = startTime - backwardTime;
            mediaPlayer.seekTo((int) startTime);
        }else{

        }
    }

    private Runnable UpdateSongTime = new Runnable() {
        public void run() {
            startTime = mediaPlayer.getCurrentPosition();
            tx1.setText(String.format("%02d:%02d",
                    TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                    TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
                                    toMinutes((long) startTime)))
            );
            seekbar.setProgress((int)startTime);
            myHandler.postDelayed(this, 100);
        }
    };

    public native int total(AssetManager mgr,String name, String path);


    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
}
