package com.example.wallpapermagazine;

import static android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.wallpapermagazine.adapter.adapter.MyFragmentAdapter;
import com.example.wallpapermagazine.fragment.FragmentCate;
import com.example.wallpapermagazine.fragment.FragmentHome;
import com.example.wallpapermagazine.fragment.FragmentLike;
import com.google.android.filament.BuildConfig;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;
import com.google.android.material.navigation.NavigationView;

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

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView bt_view;
    private ViewPager viewPager;
    private List<Fragment> mfragmentList;
    private static final int STORAGE_PERMISSION_CODE = 1;

    private NavigationView navigationView;

    private AlertDialog dialog;
    private String my_package_name, versionName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitvity_home);
        viewPager = findViewById(R.id.view_page_dis);
        bt_view = findViewById(R.id.bt_view);
        navigationView = findViewById(R.id.cata_navigation_view);
        my_package_name = getPackageName();
        versionName = getVersionName();
        inData();
        inint();
        initDrawer();
        checkStoragePermission();
        MyFragmentAdapter myFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(), mfragmentList);
        viewPager.setAdapter(myFragmentAdapter);
        bt_view.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() == R.id.view_home) {
                    viewPager.setCurrentItem(0);
                    return true;
                } else if (item.getItemId() == R.id.view_cate) {
                    viewPager.setCurrentItem(1);
                    inData();
                    return true;
                }
                {
                    viewPager.setCurrentItem(2);
                    return true;
                }

            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                onPagerSelected(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }


    private String getVersionName() {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "unknown"; // 或其他默认值
        }
    }

    private void onPagerSelected(int position) {
        switch (position) {
            case 0:
                bt_view.setSelectedItemId(R.id.view_home);
                break;
            case 1:
                bt_view.setSelectedItemId(R.id.view_cate);
                break;
            case 2:
                bt_view.setSelectedItemId(R.id.view_like);
        }
    }

    private void inData() {
        mfragmentList = new ArrayList<>();
        FragmentHome fragment1 = new FragmentHome();
        FragmentCate fragment2 = new FragmentCate();
        FragmentLike fragment3 = new FragmentLike();
        mfragmentList.add(fragment1);
        mfragmentList.add(fragment2);
        mfragmentList.add(fragment3);
    }

    private void initDrawer() {
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @SuppressLint("QueryPermissionsNeeded")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() == R.id.menu_pv) {
                    Intent intent = new Intent(MainActivity.this, PvPoActivity.class);
                    startActivity(intent);
                } else if (item.getItemId() == R.id.menu_rate) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + my_package_name));
                    if (intent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                        startActivity(intent);
                    } else {
                        // 如果没有应用可以处理，使用浏览器打开
                        intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + my_package_name));
                        startActivity(intent);
                    }
                } else if (item.getItemId() == R.id.menu_share) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=" + my_package_name);
                    sendIntent.setType("text/plain");
                    startActivity(sendIntent);
                } else {
                    showDialog();
                }
                return false;
            }
        });
    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater inflater = getLayoutInflater();
        @SuppressLint("InflateParams")
        View dialogView = inflater.inflate(R.layout.alterdialog, null);
        builder.setCustomTitle(dialogView);
        builder.setMessage("The current version is " + versionName)
                .setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    private void inint() {
        Window window = getWindow();
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        findViewById(R.id.dlt_main).setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    }
    private void checkStoragePermission() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.R) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                // 权限未被授予，申请权限
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        STORAGE_PERMISSION_CODE);
            }
        } else {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.READ_MEDIA_IMAGES},
                        STORAGE_PERMISSION_CODE);
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予
                Toast.makeText(this, "Storage permission successful", Toast.LENGTH_SHORT).show();
            } else {
                // 权限被拒绝
                Toast.makeText(this, "Storage permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

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

}
