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

import static android.app.Activity.RESULT_OK;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lc.myapplication.security.mysoundstwo.R;
import com.lc.myapplication.security.mysoundstwo.ScaryPrank;
import com.lc.myapplication.security.mysoundstwo.activity.PreviewActivity;
import com.lc.myapplication.security.mysoundstwo.activity.RecordSoundActivity;
import com.lc.myapplication.security.mysoundstwo.activity.SetNameActivity;
import com.lc.myapplication.security.mysoundstwo.adapter.RadioAdapter;
import com.lc.myapplication.security.mysoundstwo.adapter.SoundsListAdapter;
import com.lc.myapplication.security.mysoundstwo.databinding.FragmentRadioBinding;
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.MySpace;
import com.lc.myapplication.security.mysoundstwo.value.MyValue;

import java.io.IOException;
import java.util.List;

public class RadioFragment extends Fragment {
    private List<ScaryPrankLikeEntity> list;

    private int c = 1;
    private boolean isdelete = false;
    private int REQUEST_CODE_AUDIO_FILE=1;
    private Dialog dialog;
    FragmentRadioBinding binding;
    private MediaPlayer mediaPlayer;
    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentRadioBinding.inflate(inflater,container,false);
        binding.radioTitle.setTypeface(Typeface.createFromAsset(getActivity().getAssets(),"myfront1.ttf"));
        binding.addText.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "myfront2.ttf"));
        binding.radioDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isdelete = true;
                setRecycle();
            }
        });
        binding.radioAdds.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPermission();
            }
        });
        setRecycle();
        return binding.getRoot();
    }

    private void showdialog() {
        dialog = new Dialog(requireContext());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.add_sounds_dialog);
        dialog.setCancelable(true);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.findViewById(R.id.dialog_import).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("audio/*");
                startActivityForResult(Intent.createChooser(intent,"choose music file"),REQUEST_CODE_AUDIO_FILE);
                dialog.cancel();
            }
        });
        dialog.findViewById(R.id.dialog_create).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), RecordSoundActivity.class);
                getContext().startActivity(intent);
                dialog.cancel();
            }
        });
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialog.show();
        dialog.getWindow().setAttributes(lp);

    }

    private void setRecycle() {
        MyTool.RunIO(new Runnable() {
            @Override
            public void run() {
                list = ScaryPrankLikeDatabase.getScaryPrankLikeDatabase().getScaryPrankLikeDao().queryreource(c);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        RadioAdapter radioAdapter = new RadioAdapter(getActivity(),list,isdelete);
                        binding.radioRecycle.setAdapter(radioAdapter);
                        binding.radioRecycle.setLayoutManager(new GridLayoutManager(getActivity(),1));
                    }
                });
            }
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("uri","url--"+resultCode);
        if (resultCode == RESULT_OK && requestCode == 200) {
            checkPermission();
        }
        if (requestCode == REQUEST_CODE_AUDIO_FILE && resultCode == RESULT_OK){
            if (data != null){
                Uri androidurl = data.getData();
                if (androidurl != null){
                    String url = String.valueOf(androidurl);
                    Intent intent = new Intent(getContext(), SetNameActivity.class);
                    intent.putExtra(MyValue.DATA_TYPE,"LOCAL");
                    intent.putExtra(MyValue.MP3URL,url);
                    intent.putExtra(MyValue.TIME,"local music ");
                    getContext().startActivity(intent);
                }
            }
        }
    }
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), permissions, 200);
                    return;
                }
            }
            showdialog();
        } else {

        }
    }




    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == 200) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, 200);
                    return;
                }
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        setRecycle();
        isdelete = false;
    }
}