package com.app.sounds.prank.party.act;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.app.sounds.prank.party.bean.Info;
import com.app.sounds.prank.party.common.Utils;
import com.app.sounds.prank.party.common.Db;
import com.app.sounds.prank.party.common.ItemSpace;
import com.app.sounds.prank.party.databinding.RecorderFragmentBinding;
import com.app.sounds.prank.party.list.AdaLike;
import com.app.sounds.prank.party.mylistener.OnRecordListener;
import com.app.sounds.prank.party.top.AdManager;
import com.app.sounds.prank.party.top.onActionListener;

import java.util.List;
import java.util.Map;


public class RecorderFragment extends Fragment implements View.OnClickListener , OnRecordListener {

    private RecorderFragmentBinding binding;
    private AdaLike adapter;
    private ActivityResultLauncher<String> requestRecordAudioLauncher;
    private ActivityResultLauncher<String> audioPickerLauncher;
    private ActivityResultLauncher<String[]> requestStorePermissionsLauncher;

    public RecorderFragment() {

    }

    public static RecorderFragment newInstance() {
        RecorderFragment fragment = new RecorderFragment();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestRecordAudioLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestPermission(),
                isGranted -> {
                    if (isGranted) {
                        intentRecordAudio();
                    } else {
                        Toast.makeText(requireContext(), "Recording permission denied", Toast.LENGTH_SHORT).show();
                    }
                }
        );

        requestStorePermissionsLauncher = registerForActivityResult(
                new ActivityResultContracts.RequestMultiplePermissions(),
                new ActivityResultCallback<Map<String, Boolean>>() {
                    @Override
                    public void onActivityResult(Map<String, Boolean> result) {
                        Boolean isGranted = true;
                        for (Map.Entry<String, Boolean> entry : result.entrySet()) {
                            String permission = entry.getKey();
                            isGranted = entry.getValue();
                            if(!entry.getValue()){
                                isGranted = false;
                            }

                        }
                        if (isGranted) {
                            importAudio();
                        }else {
                            Toast.makeText(requireContext(),   " 权限被拒绝", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
        );
        audioPickerLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(),
                new ActivityResultCallback<Uri>() {
                    @Override
                    public void onActivityResult(Uri uri) {
                        // Handle the returned Uri

                        if (uri != null) {
                            long duration = Utils.getAudioDuration(requireContext(), uri);
                            Intent intent = new Intent(requireContext(), SaveActivity.class);
                            intent.putExtra(SaveActivity.KEY_Path, uri.toString());
                            intent.putExtra(SaveActivity.KEY_Time, duration);
                            startActivity(intent);
                        }
                    }
                });


    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = RecorderFragmentBinding.inflate(getLayoutInflater());


        ItemSpace itemHelper = new ItemSpace(10, 10, 5);
        binding.recyclerImport.addItemDecoration(itemHelper);
        binding.recyclerImport.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        List<Info> all = Db.getAllCustomization();
//        updateUi(all);
        adapter = new AdaLike(requireContext(), all,true);
        binding.recyclerImport.setAdapter(adapter);
        binding.btnimport.setOnClickListener(this);
        binding.record.setOnClickListener(this);

        return binding.getRoot();
    }





    public void refresh() {
        if (adapter != null) {
            List<Info> all = Db.getAllCustomization();
//            updateUi(all);
            adapter.updateData(all);
        }

    }

//    private void updateUi(List<Info> all) {
//        if (all.size() == 0) {
//            binding.noImportHint.setVisibility(View.VISIBLE);
//            binding.recyclerImport.setVisibility(View.GONE);
//        } else {
//            binding.noImportHint.setVisibility(View.GONE);
//            binding.recyclerImport.setVisibility(View.VISIBLE);
//        }
//    }

    private void checkAndRequestAudioPermission() {
        if (ContextCompat.checkSelfPermission(requireContext(), Utils.permission_record_audio)
                != PackageManager.PERMISSION_GRANTED) {
            requestRecordAudioLauncher.launch(Utils.permission_record_audio);
        } else {
            intentRecordAudio();
        }
    }

    private void intentRecordAudio() {
        Intent intent = new Intent(requireContext(), RecorderActivity.class);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        AdManager.showTopOn(requireActivity(), new onActionListener() {
            @Override
            public void onAction() {
                if(v.equals(binding.btnimport)){
                    onClickTimerListener(0);
                }else if(v.equals(binding.record)){
                    onClickTimerListener(1);
                }
            }
        });

    }



    private void importAudio() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/*");
        audioPickerLauncher.launch("audio/*");

    }



    public void onClickTimerListener(int type) {
        switch (type){
            case 0:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    if (ContextCompat.checkSelfPermission(requireContext(), Utils.permission_read_audio[0])
                            != PackageManager.PERMISSION_GRANTED) {
                        requestStorePermissionsLauncher.launch(Utils.permission_read_audio);
//                    ActivityCompat.requestPermissions(requireActivity(), ConstValues.permission_read_audio,
//                            ConstValues.REQUEST_READ_STORAGE_PERMISSION);
                    } else {
                        importAudio();
                    }
                } else {
                    if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED) {
                        requestStorePermissionsLauncher.launch(Utils.permission_store);
//                    ActivityCompat.requestPermissions(requireActivity(), ConstValues.permission_store, ConstValues.REQUEST_READ_STORAGE_PERMISSION);
                    } else {
                        importAudio();
                    }
                }
                break;
            case 1:
                checkAndRequestAudioPermission();
                break;
        }
    }
}