package com.prank.sounds.fart.activity;


import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
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.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.prank.sounds.fart.R;
import com.prank.sounds.fart.tools.MyUtils;
import com.prank.sounds.fart.databinding.MainActBinding;
import com.prank.sounds.fart.frag.FragLike;
import com.prank.sounds.fart.frag.FragHome;
import com.prank.sounds.fart.frag.FragRecorder;

import java.util.ArrayList;
import java.util.List;

public class MainAct extends AppCompatActivity implements View.OnClickListener {

    private MainActBinding activityMainBinding;

    private List<Fragment> fragmentList = new ArrayList<>();
    private FragLike fragLike;
    private FragRecorder fragmentRecorder;
    private ActivityResultLauncher<String> audioPickerLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = MainActBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        MyUtils.setStatusBarTextColor(this, true);
        initVp2();
        activityMainBinding.frameHome.setOnClickListener(this);
        activityMainBinding.frameAdd.setOnClickListener(this);
        activityMainBinding.frameCollect.setOnClickListener(this);
        audioPickerLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(),
                new ActivityResultCallback<Uri>() {
                    @Override
                    public void onActivityResult(Uri uri) {
                        // Handle the returned Uri
                        if (uri != null) {
                            long duration = MyUtils.getAudioDuration(MainAct.this, uri);
                            Intent intent = new Intent(MainAct.this, SaveSoundsAct.class);
                            intent.putExtra(SaveSoundsAct.KEY_Path, uri.toString());
                            intent.putExtra(SaveSoundsAct.KEY_Time, duration);
                            startActivity(intent);
                        }
                    }
                });

//        audioPickerLauncher = registerForActivityResult(
//                new ActivityResultContracts.StartActivityForResult(),
//                result -> {
//                    if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
//                        Intent data = result.getData();
//                        Uri selectedAudioUri = data.getData();
//                            if (selectedAudioUri != null) {
//                                long duration = CommonUtils.getAudioDuration(MainActivity.this, selectedAudioUri);
//                                Intent intent = new Intent(MainActivity.this, SaveActivity.class);
//                                intent.putExtra(SaveActivity.KEY_Path, selectedAudioUri.toString());
//                                intent.putExtra(SaveActivity.KEY_Time, duration);
//                                startActivity(intent);
//                            }
//
//                    }
//                }
//        );
    }

    private void initVp2() {
        fragLike = FragLike.newInstance();
        fragmentRecorder = FragRecorder.newInstance();

        fragmentList.add(FragHome.newInstance());
        fragmentList.add(fragmentRecorder);
        fragmentList.add(fragLike);
        activityMainBinding.vp2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getItemCount() {
                return fragmentList.size();
            }
        });

        activityMainBinding.vp2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        activityMainBinding.vp2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                setCurSelectTab(position);
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        int currentItem = activityMainBinding.vp2.getCurrentItem();
        if (currentItem == 1) {
            fragmentRecorder.refresh();
        } else if (currentItem == 2) {
            fragLike.refresh();
        }

    }

    private void setCurSelectTab(int position) {
        if (position == 0) {
            activityMainBinding.frameHome.setSelected(true);
            activityMainBinding.frameAdd.setSelected(false);
            activityMainBinding.frameCollect.setSelected(false);
            activityMainBinding.imHome.setSelected(true);
            activityMainBinding.imAdd.setSelected(false);
            activityMainBinding.imCollect.setSelected(false);
//            activityMainBinding.imImport.setVisibility(View.GONE);
        } else if (position == 1) {
            activityMainBinding.frameHome.setSelected(false);
            activityMainBinding.frameAdd.setSelected(true);
            activityMainBinding.frameCollect.setSelected(false);

            activityMainBinding.imHome.setSelected(false);
            activityMainBinding.imAdd.setSelected(true);
            activityMainBinding.imCollect.setSelected(false);
//            activityMainBinding.imImport.setVisibility(View.VISIBLE);
            fragmentRecorder.refresh();
        } else {
            activityMainBinding.frameHome.setSelected(false);
            activityMainBinding.frameAdd.setSelected(false);
            activityMainBinding.frameCollect.setSelected(true);

            activityMainBinding.imHome.setSelected(false);
            activityMainBinding.imAdd.setSelected(false);
            activityMainBinding.imCollect.setSelected(true);
//            activityMainBinding.imImport.setVisibility(View.GONE);
            fragLike.refresh();
        }

    }


    @Override
    public void onClick(View v) {
        if (v.equals(activityMainBinding.frameHome)) {
            activityMainBinding.vp2.setCurrentItem(0);
        } else if (v.equals(activityMainBinding.frameAdd)) {
            activityMainBinding.vp2.setCurrentItem(1);
        } else if (v.equals(activityMainBinding.frameCollect)) {
            activityMainBinding.vp2.setCurrentItem(2);
        }
//        else if (v.equals(activityMainBinding.imImport)) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
//                if (ContextCompat.checkSelfPermission(this, ConstValues.permission_read_audio[0])
//                        != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(this, ConstValues.permission_read_audio,
//                            ConstValues.REQUEST_READ_STORAGE_PERMISSION);
//                } else {
//                    importAudio();
//                }
//            } else {
//                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                        != PackageManager.PERMISSION_GRANTED ||
//                        ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
//                                != PackageManager.PERMISSION_GRANTED) {
//
//                    ActivityCompat.requestPermissions(this, 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);
        if (requestCode == MyUtils.REQUEST_READ_STORAGE_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                importAudio();
            } else {
                Toast.makeText(this, getString(R.string.permission_fail), Toast.LENGTH_SHORT).show();
            }
        }
    }

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

}