package com.fogdt.mixsample;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaCodecInfo;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fgodt.mixplayer.Core;
import com.fgodt.mixplayer.Player;
import com.fgodt.mixplayer.mixPlayerCallBack;

import java.io.File;


public class MainActivity extends AppCompatActivity implements mixPlayerCallBack {


    private long handler =0;

    AudioRecord audioRecord = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        setContentView(R.layout.activity_main);



        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);

        tv.setText("el");
        getPermission();


        if(savedInstanceState == null)
            test();
    }

    @Override
    public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
        super.onWindowAttributesChanged(params);
    }

    private Player mixplayer ;
    private void test(){

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.TOP;
        params.height = 1080*9/16;
        mixplayer = new Player(this);
        mixplayer.setMixCall(this);
        mixplayer.addMixSource("mix1",0,-1);
        mixplayer.addMixSource("silence",0,-1);
       // mixplayer.selectAudioSource("silence");
       // mixplayer.selectAudioSource("mix1");
        addContentView(mixplayer,params);
        editText = findViewById(R.id.editText);
    }

    private String getPath(){
        String  file = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_MOVIES)+"" ;
        return file;
    }

    private EditText editText;
    public void playClick(View sender){
        if(!hasRWPermission) {
            getPermission();
            return;
        }
        mixplayer.open(editText.getText().toString());
    }

    public void savedClick(View view){
        //mixplayer.selectAudioSource(editText.getText().toString());
        mixplayer.saveFile(editText.getText().toString(),getPath()+"/mixtest.mp4");
        //mixplayer.saveFile(editText.getText().toString(),"rtmp://192.168.3.10/live/abc1234");
    }

    //10s pcm data
    int totalLen = 4*44100*10;
    byte[] pcmData = new byte[4*44100*10];
    int pcmWritePos = 0;
    public void closeClick(View sender){
       mixplayer.stop();
    }

    public void recorderClick(View view){
        if(!hasRcordPermission) {
            getPermission();
            return;
        }


        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,44100, AudioFormat.CHANNEL_IN_STEREO,AudioFormat.ENCODING_PCM_16BIT,4096*3);
        if(audioRecord.getState() != AudioRecord.STATE_INITIALIZED){
            Toast.makeText(this,"初始化录音失败",Toast.LENGTH_SHORT).show();
            return;
        }

        if(audioRecord != null){
            audioRecord.startRecording();
            pcmWritePos = 0;
            pcmReadPos = 0;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (pcmWritePos<totalLen){
                        int wlen = totalLen-pcmWritePos > 4096? 4096:totalLen-pcmWritePos;
                        int ret = audioRecord.read(pcmData,pcmWritePos,wlen);
                        pcmWritePos+=ret;
                    }
                    audioRecord.stop();
                }
            }).start();
        }
    }

    public void playerAndResume(View view){
        if(mixplayer.getStatus() == mixplayer.STATUS_PAUSE){
            mixplayer.resume();
        }else if(mixplayer.getStatus() == mixplayer.STATUS_RUNNING){
            mixplayer.pause();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }


    int pcmReadPos = 0;
    @Override
    public int mix_call(String name, byte[] data, int len) {
        if(name.equals("silence")){
            return 0;
        }
        if(totalLen - pcmReadPos < len){
            return 0;
        }else {
            System.arraycopy(pcmData,pcmReadPos,data,0,len);
            pcmReadPos += len;
            return len;
        }
    }

    @Override
    public void closeMsg(String msg) {
        Toast.makeText(this,"MIX CLOSE",Toast.LENGTH_SHORT).show();
    }


    private boolean hasRWPermission = false;
    private boolean hasRcordPermission = false;

    private  void getPermission(){
        int has = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (has == PackageManager.PERMISSION_GRANTED){
            hasRWPermission = true;
        }else {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE  },1);
        }

        has = ContextCompat.checkSelfPermission(getApplication(), Manifest.permission.RECORD_AUDIO);
        if (has == PackageManager.PERMISSION_GRANTED){
            hasRcordPermission = true;
        }else {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECORD_AUDIO},2);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        if(requestCode == 1){
            if(grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                hasRWPermission = true;
            }else {
                if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                    new AlertDialog.Builder(this)
                            .setMessage("need read write permisson")
                            .setPositiveButton("ok",(d,w)->{
                                if (w == DialogInterface.BUTTON_POSITIVE){
                                    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                                }
                            })
                            .setNegativeButton("cancle",null)
                            .setTitle("需要提供相应权限")
                            .create()
                            .show();
                }
            }
        }
        if (requestCode == 2){
            if(grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                hasRcordPermission = true;
            }else {
                if(ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.RECORD_AUDIO)){
                    new AlertDialog.Builder(this)
                            .setMessage("need record audio permisson")
                            .setPositiveButton("ok",(dialog,which)->{
                                if (which == DialogInterface.BUTTON_POSITIVE){
                                    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECORD_AUDIO},1);
                                }
                            })
                            .setNegativeButton("cancle",null)
                            .setTitle("需要录音权限")
                            .create()
                            .show();
                }
            }
        }
    }

}
