package com.fun.funnyprank.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

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 com.fun.funnyprank.R;
import com.fun.funnyprank.activity.RecordActivity;
import com.fun.funnyprank.activity.SaveActivity;
import com.fun.funnyprank.adapter.CustomAdapter;
import com.fun.funnyprank.data.LikeData;
import com.fun.funnyprank.data.Mydata;
import com.fun.funnyprank.data.MydataBase;
import com.fun.funnyprank.data.StaticValue;
import com.fun.funnyprank.databinding.FragmentCustomBinding;

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


public class CustomFragment extends Fragment {
    FragmentCustomBinding binding;
    private CustomAdapter customAdapter;
    private Dialog dialog;
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private static final int REQUEST_READ_STORAGE_PERMISSION = 500;
    private static final int REQUEST_PICK_AUDIO = 300;
    private String[] permissions = {Manifest.permission.RECORD_AUDIO};
    private String[] permission = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private boolean show = false;

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

        initData();

        initEvent();

        return binding.getRoot();
    }

    private void initData() {
        customAdapter = new CustomAdapter(requireActivity());
        binding.customRv.setLayoutManager(new LinearLayoutManager(requireContext()));
        MydataBase.getInstance().likeDao().getCustom("custom").observe(getViewLifecycleOwner(), new Observer<List<LikeData>>() {
            @Override
            public void onChanged(List<LikeData> mydata) {
                if (!mydata.isEmpty()) {
                    initView(mydata);
                } else {
                    show = false;
                    customAdapter.showDelete(false);
                    binding.customDelete.setVisibility(View.GONE);
                    binding.addHide.setVisibility(View.VISIBLE);
                    binding.addTips.setVisibility(View.VISIBLE);
                    binding.add.setVisibility(View.GONE);
                    binding.customRv.setVisibility(View.GONE);
                }
            }
        });
    }

    private void initView(List<LikeData> customData) {
        binding.customDelete.setVisibility(View.VISIBLE);
        binding.addHide.setVisibility(View.GONE);
        binding.addTips.setVisibility(View.GONE);
        binding.add.setVisibility(View.VISIBLE);
        binding.customRv.setVisibility(View.VISIBLE);
        customAdapter.SetData(customData);
        binding.customRv.setAdapter(customAdapter);
    }

    private void initEvent() {
        binding.add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
        binding.addHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
        binding.customDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show = !show;
                customAdapter.showDelete(show);
            }
        });
    }

    private void showDialog() {
        dialog = new Dialog(requireContext());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog);
        dialog.setCancelable(true);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(dialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;

        dialog.findViewById(R.id.dialog_import).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_MEDIA_AUDIO)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(requireActivity(),
                                new String[]{Manifest.permission.READ_MEDIA_AUDIO},
                                REQUEST_READ_STORAGE_PERMISSION);
                    } else {
                        importAudio();
                    }
                } else {
                    if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED ||
                            ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED) {

                        ActivityCompat.requestPermissions(requireActivity(), permission, REQUEST_READ_STORAGE_PERMISSION);
                    } else {
                        importAudio();
                    }
                }


            }
        });
        dialog.findViewById(R.id.dialog_record).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.RECORD_AUDIO)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(requireActivity(), permissions, REQUEST_RECORD_AUDIO_PERMISSION);
                } else {
                    Intent intent = new Intent(requireContext(), RecordActivity.class);
                    startActivity(intent);
                }

            }
        });

        dialog.show();
        dialog.getWindow().setAttributes(lp);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_PICK_AUDIO && resultCode == getActivity().RESULT_OK) {
            if (data != null) {
                Uri selectedAudioUri = data.getData();
                if (selectedAudioUri != null) {
                    long duration = getAudioDuration(requireContext(), selectedAudioUri);
                    Intent intent = new Intent(requireContext(), SaveActivity.class);
                    intent.putExtra(StaticValue.KEY_Path, selectedAudioUri.toString());
                    intent.putExtra(StaticValue.KEY_Time, duration);
                    startActivity(intent);
                }
            }
        }
    }

    private long getAudioDuration(Context context, Uri uri) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        long duration = 0;

        try {
            ContentResolver contentResolver = context.getContentResolver();
            retriever.setDataSource(context, uri);
            String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            duration = Long.parseLong(time);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return duration;
    }

    private void importAudio() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("audio/*");
        startActivityForResult(Intent.createChooser(intent, "Select Audio"), REQUEST_PICK_AUDIO);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (dialog != null) {
            dialog.dismiss();
        }
    }
}