package com.example.wallpapermagazine.fragment;

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.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wallpapermagazine.LoveDAO.AppDatabase;
import com.example.wallpapermagazine.LoveDAO.FavoriteImage;
import com.example.wallpapermagazine.PvPoActivity;
import com.example.wallpapermagazine.R;
import com.example.wallpapermagazine.Recycle_view;
import com.example.wallpapermagazine.ViewActivity2;
import com.example.wallpapermagazine.action.FavoriteLimage;
import com.example.wallpapermagazine.recylcle.FavoriteImageAdapter;
import com.google.android.material.navigation.NavigationView;

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

public class FragmentLike extends Fragment implements FavoriteLimage {
    private FavoriteImageAdapter adapter;
    private List<FavoriteImage> favoriteImages = new ArrayList<>();
    private AppDatabase appDatabase;
    private RecyclerView recyclerView;
    private DrawerLayout drawerLayout;
    private ImageView imageView;
    private NavigationView navigationView;
    private String my_package_name,versionName;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_like, container, false);
        appDatabase = AppDatabase.getDatabase(requireContext());
        recyclerView = view.findViewById(R.id.recyl_like);
        imageView = view.findViewById(R.id.like_more);
        navigationView = requireActivity().findViewById(R.id.cata_navigation_view);
        my_package_name=requireActivity().getPackageName();
        versionName=getVersionName();
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() == R.id.menu_pv) {
                    Intent intent = new Intent(requireContext(), 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(requireActivity().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;
            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout = requireActivity().findViewById(R.id.dlt_main);
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        setRecyclerviewWallpaper();
        loadFavoriteImages();
        return view;
    }


    private void setRecyclerviewWallpaper() {
        Recycle_view recycle_View = new Recycle_view(16, 20, 0);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addItemDecoration(recycle_View);
        adapter = new FavoriteImageAdapter(getActivity(), favoriteImages);
        adapter.setInfoWallPaperListener((FavoriteLimage) this);
        recyclerView.setAdapter(adapter);
    }
    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        LayoutInflater inflater = getLayoutInflater();
        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) {
                    }
                });

        // 创建并显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private String getVersionName() {
        try {
            PackageInfo packageInfo = requireActivity().getPackageManager().getPackageInfo(requireActivity().getPackageName(), 0);return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "unknown"; // 或其他默认值
        }
    }
    private void loadFavoriteImages() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<FavoriteImage> allFavoriteImages = appDatabase.favoriteImageDao().getAllFavoriteImages();
                requireActivity().runOnUiThread(new Runnable() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void run() {
                        favoriteImages.clear();
                        favoriteImages.addAll(allFavoriteImages);
                        adapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }
    @Override
    public void onItemClickAction(FavoriteImage favoriteImage, int recop) {
        Intent intent = new Intent(requireActivity(), ViewActivity2.class);
        intent.putExtra("recop", recop);
        intent.putExtra("imageUrl", favoriteImage);
        startActivity(intent);
    }
    public class LoadFavoriteImagesTask extends AsyncTask<Void, Void, List<FavoriteImage>> {
        @Override
        protected List<FavoriteImage> doInBackground(Void... voids) {
            return appDatabase.favoriteImageDao().getAllFavoriteImages();
        }

        @SuppressLint("NotifyDataSetChanged")
        @Override
        protected void onPostExecute(List<FavoriteImage> images) {
            favoriteImages.clear();
            favoriteImages.addAll(images);
            adapter.notifyDataSetChanged();
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        loadFavoriteImages();
    }
}
