package com.prank.sound.app.pageview;

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.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.prank.sound.app.adapter.FavoriteAdapter;
import com.prank.sound.app.databinding.FragmentRecordSoundsBinding;
import com.prank.sound.app.mydata.ChildData;
import com.prank.sound.app.myutils.MyValues;
import com.prank.sound.app.myutils.ObUtils;
import com.prank.sound.app.myutils.Utils;

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


public class RecordFragment extends Fragment implements View.OnClickListener {


    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private FragmentRecordSoundsBinding binding;
    private FavoriteAdapter adapter;
    private ActivityResultLauncher<String> requestRecordAudioLauncher;
    private ActivityResultLauncher<String> audioPickerLauncher;
    private ActivityResultLauncher<String[]> requestStorePermissionsLauncher;

    public RecordFragment() {
        // Required empty public constructor
    }

    public static RecordFragment newInstance() {
        RecordFragment fragment = new RecordFragment();
        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        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) {
//
//                                Toast.makeText(requireContext(), permission + " 权限已授予", Toast.LENGTH_SHORT).show();
//                            } else {
//                                // 权限被拒绝
//                                Toast.makeText(requireContext(), permission + " 权限被拒绝", Toast.LENGTH_SHORT).show();
//                            }
                        }
                        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(), StoreSoundsActivity.class);
                            intent.putExtra(StoreSoundsActivity.KEY_Path, uri.toString());
                            intent.putExtra(StoreSoundsActivity.KEY_Time, duration);
                            startActivity(intent);
                        }
                    }
                });
    }

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

        binding.imImport.setOnClickListener(this);
        binding.recyclerImport.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        List<ChildData> all = ObUtils.getAllCustomization();
        updateUi(all);
        adapter = new FavoriteAdapter(requireContext(), all);
        binding.recyclerImport.setAdapter(adapter);
        binding.recordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAndRequestAudioPermission();
            }
        });

        return binding.getRoot();
    }


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

    }

    private void updateUi(List<ChildData> 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(), MyValues.permission_record_audio)
                != PackageManager.PERMISSION_GRANTED) {
            requestRecordAudioLauncher.launch(MyValues.permission_record_audio);
        } else {
            intentRecordAudio();
        }
    }

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

    @Override
    public void onClick(View v) {
        if (v.equals(binding.imImport)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                if (ContextCompat.checkSelfPermission(requireContext(), MyValues.permission_read_audio[0])
                        != PackageManager.PERMISSION_GRANTED) {
                    requestStorePermissionsLauncher.launch(MyValues.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(MyValues.permission_store);
//                    ActivityCompat.requestPermissions(requireActivity(), ConstValues.permission_store, ConstValues.REQUEST_READ_STORAGE_PERMISSION);
                } else {
                    importAudio();
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

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

    }
}