package com.prankster.fx.ui.activity;


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.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gyf.immersionbar.ImmersionBar;
import com.prankster.fx.FXApp;
import com.prankster.fx.R;
import com.prankster.fx.databinding.ActivityMainBinding;
import com.prankster.fx.db.Bean;
import com.prankster.fx.db.Category;
import com.prankster.fx.topon.AdManager;
import com.prankster.fx.ui.fragment.FXHomeFg;
import com.prankster.fx.ui.fragment.FXLikeFg;
import com.prankster.fx.ui.fragment.FXRecordFg;
import com.prankster.fx.utils.CommonUtils;
import com.prankster.fx.utils.ConstValues;

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

public class FXMainAct extends AppCompatActivity implements View.OnClickListener {

    private ActivityMainBinding activityMainBinding;

    private List<Fragment> fragmentList = new ArrayList<>();
    private FXLikeFg fxLikeFg;
    private FXRecordFg fxRecordFg;
    private ActivityResultLauncher<String> audioPickerLauncher;

    private MediaPlayer mediaPlayer;
    private Bean bean;
    private List<Bean> list;
    private boolean first = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(activityMainBinding.getRoot());
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .statusBarView(activityMainBinding.view)
                .init();
        AdManager.loadAllAd();
        initAudioData();
        initVp2();
        activityMainBinding.frameHome.setOnClickListener(this);
        activityMainBinding.frameAdd.setOnClickListener(this);
        activityMainBinding.frameCollect.setOnClickListener(this);
        activityMainBinding.imImport.setOnClickListener(this);

        audioPickerLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(),
                uri -> {
                    // Handle the returned Uri
                    if (uri != null) {
                        long duration = CommonUtils.getAudioDuration(FXMainAct.this, uri);
                        Intent intent = new Intent(FXMainAct.this, FXSaveAudioAct.class);
                        intent.putExtra(FXSaveAudioAct.KEY_Path, uri.toString());
                        intent.putExtra(FXSaveAudioAct.KEY_Time, duration);
                        startActivity(intent);
                    }
                });


        activityMainBinding.linearPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    activityMainBinding.btnPlay.setSelected(false);
                    return;
                }
                if (first) {
                    activityMainBinding.btnPlay.setSelected(true);
                    first = false;
                    mediaPlayer.start();
                } else {
                    playAudio(true);
                }


            }
        });
    }

    private void initVp2() {
        fxLikeFg = FXLikeFg.newInstance();
        fxRecordFg = FXRecordFg.newInstance();
        fragmentList.add(FXHomeFg.newInstance());
        fragmentList.add(fxRecordFg);
        fragmentList.add(fxLikeFg);
        activityMainBinding.vp2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentList.get(position);
            }

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

        // 获取每个Tab下方的指示线
        View indicatorHome = findViewById(R.id.indicator_home);
        View indicatorAdd = findViewById(R.id.indicator_add);
        View indicatorCollect = findViewById(R.id.indicator_collect);


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

                // 隐藏所有指示线
                indicatorHome.setVisibility(View.GONE);
                indicatorAdd.setVisibility(View.GONE);
                indicatorCollect.setVisibility(View.GONE);

                // 根据选中的Tab显示对应的指示线
                if (position == 0) {
                    indicatorHome.setVisibility(View.VISIBLE);
                } else if (position == 1) {
                    indicatorAdd.setVisibility(View.VISIBLE);
                } else if (position == 2) {
                    indicatorCollect.setVisibility(View.VISIBLE);
                }
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        int currentItem = activityMainBinding.vp2.getCurrentItem();
        Log.d("----------", "---------currentItem=" + currentItem);
        if (currentItem == 1) {
            fxRecordFg.refresh();
        } else if (currentItem == 2) {
            fxLikeFg.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);
            activityMainBinding.randomPlayLayout.setVisibility(View.VISIBLE);
        } else if (position == 1) {
            activityMainBinding.imHome.setSelected(false);
            activityMainBinding.imAdd.setSelected(true);
            activityMainBinding.imCollect.setSelected(false);
            activityMainBinding.imImport.setVisibility(View.VISIBLE);
            activityMainBinding.randomPlayLayout.setVisibility(View.GONE);
            fxRecordFg.refresh();
        } else {
            activityMainBinding.imHome.setSelected(false);
            activityMainBinding.imAdd.setSelected(false);
            activityMainBinding.imCollect.setSelected(true);
            activityMainBinding.imImport.setVisibility(View.GONE);
            activityMainBinding.randomPlayLayout.setVisibility(View.GONE);
            fxLikeFg.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/*");

    }


    private void initAudioData() {
        list = new ArrayList<>();
        for (Category category : FXApp.bean) {
            list.addAll(category.getBeanList());
        }
        initAudio();
    }

    private void initAudio() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                activityMainBinding.btnPlay.setSelected(false);
            }
        });
        playAudio(false);
    }


    private void playAudio(boolean play) {
        Collections.shuffle(list);
        bean = list.get(0);
        Glide.with(this)
                .load(bean.getCovert())
                .placeholder(R.drawable.tab_home_no)
                .into(activityMainBinding.audioIm);
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(bean.getAudioUrl());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (play) {
                        activityMainBinding.btnPlay.setSelected(true);
                        mediaPlayer.start();
                    }
                }
            });

        } catch (IOException ioException) {


        }
    }
}