package com.lc.myapplication.security.mysoundstwo.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AppOpsManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.room.util.FileUtil;

import com.lc.myapplication.security.mysoundstwo.R;
import com.lc.myapplication.security.mysoundstwo.value.MyValue;

import org.xml.sax.ext.DeclHandler;

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

public class RecordSoundActivity extends FragmentActivity {
    private RelativeLayout recore_button;
    private RelativeLayout main_record;
    private ImageView record_back;
    private TextView record_text_time;
    private boolean isrecord = false;
    private MediaRecorder mediaRecorder;
    private String filename;
    int timeCount;
    Thread timeThread;
    final int TIME_COUNT = 0x101;
    private File androidfile;
    private int count;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_sound);
        main_record = findViewById(R.id.main_record);
        setbackground();
        record_back = findViewById(R.id.record_back);
        record_text_time = findViewById(R.id.record_text_time);
        recore_button = findViewById(R.id.record_button);
        onMyClick();
    }
    private void setbackground() {
        Window window = getWindow();
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        main_record.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    }


    private void onMyClick() {
        record_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        recore_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isrecord) {
                    stopRecordAudio();
                } else {
                    startRecord();
                }
            }
        });
    }

    private void stopRecordAudio() {
        if (mediaRecorder != null) {
            try {
                mediaRecorder.stop();//停止录音
                mediaRecorder.release();//释放
                String name = androidfile.getAbsolutePath();
                String time = FormatMiss(count);
                //Log.d("time","time"+time);
                Intent intent = new Intent(this, SetNameActivity.class);
                //Log.d("-----name","name"+name);
                intent.putExtra(MyValue.MP3URL,name);
                intent.putExtra(MyValue.TIME, time);
                //intent.putExtra(MyValue.DATA_TYPE,"LOAD");
                startActivity(intent);
                finish();
                mediaRecorder = null;//置空
            } catch (Exception exception) {
                mediaRecorder.reset();
                mediaRecorder.release();
                mediaRecorder = null;
            }
        }
        recore_button.setBackgroundResource(R.drawable.record_play_src);
        isrecord = false;
    }

    @SuppressLint("NewApi")
    private void startRecord() {
        isrecord = true;
        recore_button.setBackgroundResource(R.drawable.record_stop_src);
            File filepath = this.getCacheDir();  //声明存储路径，用绝对路径什么都可以
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");// HH:mm:ss
            //获取当前时间
            Date date = new Date(System.currentTimeMillis());
            filename = simpleDateFormat.format(date);
            androidfile = new File(filepath, filename+"RADIO.mp3");
            if (mediaRecorder == null) {
                mediaRecorder = new MediaRecorder();
            }
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置麦克风
            //Log.d("pathfile1", "pathfile" + androidfile);
        /*
          设置保存输出文件的格式：THREE_GPP/MPEG-4/RAW_AMR/Default THREE_GPP(3gp格式，H263视频/ARM音频编码)、MPEG-4、RAW_AMR(只支持音频且音频编码要求为AMR_NB)
         */
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);//文件编码格式
        //设置音频文件的存储方式
        if(Build.VERSION.SDK_INT < 26){
            //若api低于26，调用setOutputFile(String path)
            mediaRecorder.setOutputFile(androidfile.getAbsolutePath());//返回文件的绝对路径
        }else {
            //若API高于26 使用setOutputFile(File path)
            mediaRecorder.setOutputFile(androidfile);
        }
        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
            timeThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    countTime();
                }
            });
            timeThread.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private void countTime() {
        while (isrecord) {
            //LogUtil.d("正在录音");
            timeCount++;
            Message msg = Message.obtain();
            msg.what = TIME_COUNT;
            msg.obj = timeCount;
            myHandler.sendMessage(msg);
            try {
                timeThread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //LogUtil.d("结束录音");
        timeCount = 0;
        Message msg = Message.obtain();
        msg.what = TIME_COUNT;
        msg.obj = timeCount;
        myHandler.sendMessage(msg);
    }
    public static String FormatMiss(int miss) {
        String hh = miss / 3600 > 9 ? miss / 3600 + "" : "0" + miss / 3600;
        String mm = (miss % 3600) / 60  > 9 ? (miss % 3600) / 60 + "" : "0" + (miss % 3600) / 60;
        String ss = (miss % 3600) % 60  > 9 ? (miss % 3600) % 60 + "" : "0" + (miss % 3600) % 60;
        return hh + ":" + mm + ":" + ss;
    }
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIME_COUNT:
                    count = (int) msg.obj;
                    //LogUtil.d("count == " + count);
                    record_text_time.setText(FormatMiss(count));
                    break;
            }
        }
    };
}