package com.prank.master.ui;


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.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

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.util.Log;
import android.view.View;
import android.widget.Toast;

import com.prank.master.R;
import com.prank.master.databinding.ActivityMainBinding;
import com.prank.master.topon.AdManager;
import com.prank.master.utils.CommonUtils;
import com.prank.master.utils.ConstValues;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityMainBinding activityMainBinding;

    private List<Fragment> fragmentList = new ArrayList<>();
    private LikeFragment likeFragment;
    private RecordFragment recordFragment;
    private ActivityResultLauncher<String> audioPickerLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        CommonUtils.setStatusBarTextColor(this, true);
        AdManager.loadAllAd();
        initVp2();
        activityMainBinding.frameHome.setOnClickListener(this);
        activityMainBinding.frameAdd.setOnClickListener(this);
        activityMainBinding.frameCollect.setOnClickListener(this);
        activityMainBinding.imImport.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 = CommonUtils.getAudioDuration(MainActivity.this, uri);
                            Intent intent = new Intent(MainActivity.this, SaveAudioActivity.class);
                            intent.putExtra(SaveAudioActivity.KEY_Path, uri.toString());
                            intent.putExtra(SaveAudioActivity.KEY_Time, duration);
                            startActivity(intent);
                        }
                    }
                });


    }

    private void initVp2() {
        likeFragment = LikeFragment.newInstance();
        recordFragment = RecordFragment.newInstance();
        fragmentList.add(HomeFragment.newInstance());
        fragmentList.add(recordFragment);
        fragmentList.add(likeFragment);
        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();
        Log.d("----------", "---------currentItem=" + currentItem);
        if (currentItem == 1) {
            recordFragment.refresh();
        } else if (currentItem == 2) {
            likeFragment.refresh();
        }

    }

    private void setCurSelectTab(int position) {
        if (position == 0) {
            activityMainBinding.imHome.setSelected(true);
            activityMainBinding.imAdd.setSelected(false);
            activityMainBinding.imCollect.setSelected(false);
            activityMainBinding.imImport.setVisibility(View.GONE);
        } else if (position == 1) {
            activityMainBinding.imHome.setSelected(false);
            activityMainBinding.imAdd.setSelected(true);
            activityMainBinding.imCollect.setSelected(false);
            activityMainBinding.imImport.setVisibility(View.VISIBLE);
            recordFragment.refresh();
        } else {
            activityMainBinding.imHome.setSelected(false);
            activityMainBinding.imAdd.setSelected(false);
            activityMainBinding.imCollect.setSelected(true);
            activityMainBinding.imImport.setVisibility(View.GONE);
            likeFragment.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 == ConstValues.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/*");

    }

}