package com.example.mynotepad.MenuFeatures.VoiceMassages;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.os.SystemClock;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.mynotepad.MenuFeatures.Utils;
import com.example.mynotepad.R;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class RecordFragment extends Fragment implements View.OnClickListener {

    private NavController navController;
    private ImageView listBtn;
    private ImageButton recordBtn;
    private boolean isRecording = false;
    private MediaRecorder mRecorder;
    private String fileName = null;
    private Chronometer chronometer;
    private int RECORD_AUDIO_REQUEST_CODE = 123;
    private RelativeLayout layout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_record, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getPermissionToRecordAudio();
        }
        init(view);
        setBg(Utils.sTheme);
    }

    private void setBg(String sTheme) {
        switch (sTheme) {
            case "dark":
                layout.setBackgroundResource(R.drawable.main_bg_dark);
                break;
            case "bright":
                layout.setBackgroundResource(R.drawable.main_bg_bright);
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void getPermissionToRecordAudio() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    RECORD_AUDIO_REQUEST_CODE);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if (requestCode == RECORD_AUDIO_REQUEST_CODE) {
            if (grantResults.length == 3 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getContext(), "accepted", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "You must give permissions to use this app. App is exiting.", Toast.LENGTH_SHORT).show();
                getActivity().finish();
            }
        }

    }

    private void init(View view) {
        navController = Navigation.findNavController(view);
        listBtn = view.findViewById(R.id.recordList);
        recordBtn = view.findViewById(R.id.recordBtn);
        chronometer = view.findViewById(R.id.chronometerTimer);
        layout = view.findViewById(R.id.layout);

        listBtn.setOnClickListener(this);
        recordBtn.setOnClickListener(this);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.recordList: {
                navController.navigate(R.id.action_recordFragment_to_audioListFragment);
                break;
            }
            case R.id.recordBtn: {
                if (isRecording) {
                    //stop recording
                    isRecording = false;
                    recordBtn.setBackground(getResources().getDrawable(R.drawable.start_stop_bg));
                    stopRecording();
                } else {
                    //start recording
                    isRecording = true;
                    recordBtn.setBackground(getResources().getDrawable(R.drawable.stop_btn_bg));
                    startRecording();
                }
                break;
            }
        }
    }


    private void startRecording() {
        File root = android.os.Environment.getExternalStorageDirectory();
        File file = new File(root.getAbsolutePath() + "/NotepadVoiceRecorder/Audios");//create a 2 folders inside each other to save voices
        if (!file.exists()) {
            file.mkdirs();//create a the folders if it does not exists
        }
        fileName = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss" , Locale.CANADA).format(new Date()) + ".mp3";
        Log.e("filename", root.getAbsolutePath() + "/NotepadVoiceRecorder/Audios/" + fileName);

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile( root.getAbsolutePath() + "/NotepadVoiceRecorder/Audios/" +fileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        try {
            if (mRecorder!=null){
                mRecorder.prepare();
                mRecorder.start();}
            chronometer.setBase(SystemClock.elapsedRealtime());// to start from 00:00
            chronometer.start();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("IOException",e.getMessage()+"");
        }

    }


    private void stopRecording() {
        if (mRecorder!=null)
       { mRecorder.stop();
        mRecorder.release();}
        mRecorder = null;
        chronometer.stop();
        chronometer.setBase(SystemClock.elapsedRealtime());
        Toast.makeText(getContext(), "Recording saved successfully.", Toast.LENGTH_SHORT).show();
    }
}