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

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.lc.myapplication.security.mysoundstwo.R;
import com.lc.myapplication.security.mysoundstwo.room.ScaryPrankLikeDatabase;
import com.lc.myapplication.security.mysoundstwo.room.ScaryPrankLikeEntity;
import com.lc.myapplication.security.mysoundstwo.tool.MyTool;
import com.lc.myapplication.security.mysoundstwo.value.MyValue;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

public class SetNameActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer;
    private String path;
    private String mp3url;
    private Uri localmp3uri;
    private String type;
    private EditText set_name;
    private RelativeLayout mian_setname;
    private Button set_name_play;
    private boolean isplay = false;
    private RelativeLayout save_name;
    private String name;
    private String time;
    private ScaryPrankLikeEntity scaryPrankLikeEntity;
    private int c = 1;
    private ScaryPrankLikeEntity exitname;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_name);
        mian_setname = findViewById(R.id.main_setname);
        setbackground();
        set_name = findViewById(R.id.set_name);
        set_name_play = findViewById(R.id.set_name_play);
        save_name = findViewById(R.id.save_name);
        getData();
        OnMyClick();
    }
    private void setbackground() {
        Window window = getWindow();
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        mian_setname.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    }

    private void OnMyClick() {
        set_name_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isplay){
                    isplay = false;
                    set_name_play.setBackgroundResource(R.drawable.record_play_src);
                    if (mediaPlayer != null){
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }
                }else {
                    set_name_play.setBackgroundResource(R.drawable.record_stop_src);
                    mediaPlayer = new MediaPlayer();
                    if (Objects.equals(type, "LOCAL")){
                        try {
                            mediaPlayer.setDataSource(path);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }else {
                        try {
                            mediaPlayer.setDataSource(mp3url);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mediaPlayer.start();
                        }
                    });
                    isplay = true;
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            set_name_play.setBackgroundResource(R.drawable.record_play_src);
                        }
                    });
                }
            }
        });
        save_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(SetNameActivity.this,getString(R.string.save_name_wait),Toast.LENGTH_SHORT).show();
                name = set_name.getText().toString();
                MyTool.RunIO(new Runnable() {
                    @Override
                    public void run() {
                        exitname = ScaryPrankLikeDatabase.getScaryPrankLikeDatabase().getScaryPrankLikeDao().QueryLikeName(name);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (exitname == null){
                                    setEntity();
                                    MyTool.RunIO(new Runnable() {
                                        @Override
                                        public void run() {
                                            ScaryPrankLikeDatabase.getScaryPrankLikeDatabase().getScaryPrankLikeDao().insertLikeData(scaryPrankLikeEntity);
                                        }
                                    });
                                    Toast.makeText(SetNameActivity.this,getString(R.string.save_name_success),Toast.LENGTH_LONG).show();
                                    finish();
                                }else {
                                    Toast.makeText(SetNameActivity.this,getString(R.string.name_exit),Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    }
                });
            }
        });
    }

    private void setEntity() {
        scaryPrankLikeEntity = new ScaryPrankLikeEntity();
        scaryPrankLikeEntity.setName(name);
        if (Objects.equals(type, "LOCAL")) {
            scaryPrankLikeEntity.setMp3url(path);
        }else {
            scaryPrankLikeEntity.setMp3url(mp3url);
        }
        scaryPrankLikeEntity.setSoundslike(false);
        scaryPrankLikeEntity.setResource(c);
        scaryPrankLikeEntity.setTime(time);
    }


    private void getData() {
        Intent intent = getIntent();
        type = intent.getStringExtra(MyValue.DATA_TYPE);
        mp3url = intent.getStringExtra(MyValue.MP3URL);
        time = intent.getStringExtra(MyValue.TIME);
        if (Objects.equals(type, "LOCAL")) {
            path = gotoGetsource(this,mp3url);
        }
    }

    private String gotoGetsource(Context context,String mp3urlpath) {
        Uri uripath = Uri.parse(mp3urlpath);
        ContentResolver contentResolver = context.getContentResolver();//ContentResolver是用于操作数据，与此对应的是ContentProdiver
        try {
            InputStream fst = contentResolver.openInputStream(uripath);
            FileOutputStream fileOutputStream = new FileOutputStream(new File(getCacheDir(),"local_music.mp3"));
            if (fst == null){
                return null;
            }
            byte[] butter = new byte[1024];
            int n;
            while((n = fst.read(butter)) != -1) {
                fileOutputStream.write(butter,0,n);
            }
            return new File(getCacheDir(),"local_music.mp3").getAbsolutePath();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}