package com.example.wallpapermagazine;

import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.wallpapermagazine.LoveDAO.AppDatabase;
import com.example.wallpapermagazine.LoveDAO.FavoriteImage;
import com.example.wallpapermagazine.LoveDAO.FavoriteImageDao;
import com.example.wallpapermagazine.action.DownloadListener;
import com.example.wallpapermagazine.action.onActionListener;
import com.example.wallpapermagazine.donwload.ImageDownloadTask;
import com.example.wallpapermagazine.fragment.PreviewFragment;
import com.example.wallpapermagazine.recylcle.FavoriteImageAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

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

public class ViewActivity2 extends AppCompatActivity {
    private ImageView frameLayoutBack;
    private ViewPager viewPagerPreview;
    private FavoriteImage favoriteImage;
    private FavoriteImageAdapter adapter;
    private AppDatabase appDatabase;
    private WallpaperManager wallpaperManager;
    private FloatingActionButton fab_download, fab_like, fab_share;
    private String lovePreImg;
    private TextView textViewLoading;
    private FavoriteImageDao favoriteImageDao;
    private int recop;
    private static final int STORAGE_PERMISSION_CODE = 1;

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewlayout2);
//        MaxManager.onLoadAd();
        // TODO: 2024/9/23 Ad 
        inint();
        favoriteImage = new FavoriteImage();
        appDatabase = AppDatabase.getDatabase(this);
        favoriteImageDao = appDatabase.favoriteImageDao();
        favoriteImage = (FavoriteImage) getIntent().getSerializableExtra("imageUrl");
        recop = getIntent().getIntExtra("recop", 0);
        lovePreImg = favoriteImage.getImageUrl();
        wallpaperManager = WallpaperManager.getInstance(this);
        frameLayoutBack = findViewById(R.id.imageview_back2);
        viewPagerPreview = findViewById(R.id.viewpager_preview);
        textViewLoading = findViewById(R.id.textview_loading2);
        fab_download = findViewById(R.id.fbt_download2);
        fab_share = findViewById(R.id.fbt_show2);
        fab_like = findViewById(R.id.fbt_love2);
        initViewPaper();
        frameLayoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.set_wallpaper).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showMax(new onActionListener() {
                    @Override
                    public void onAction() {
                        if (lovePreImg != null) {
                            loadPreview(lovePreImg);
                        } else {
                            Toast.makeText(ViewActivity2.this, "Sorry setting failed", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
        fab_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fab_share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent shareIntent = new Intent(Intent.ACTION_SEND);
                        shareIntent.setType("text/plain"); // 设置分享内容的类型为图片
                        shareIntent.putExtra(Intent.EXTRA_TEXT, lovePreImg); // 可以添加URL文本
                        startActivity(Intent.createChooser(shareIntent, "Share pictures"));
                    }
                });
            }
        });
        fab_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (lovePreImg != null) {
                    textViewLoading.setVisibility(View.VISIBLE);
                    String imageUrl = lovePreImg;
                    ImageDownloadTask downloadTask = new ImageDownloadTask(getBaseContext(), new DownloadListener() {
                        @Override
                        public void downloadResult(boolean isSuccess) {
                            textViewLoading.setVisibility(View.GONE);
                            if (isSuccess) {
                                Toast.makeText(ViewActivity2.this, "Image downloaded successfully", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(ViewActivity2.this, "Failed to download image", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    downloadTask.execute(imageUrl);
                }

            }
        });
        favoriteImage.imageUrl = lovePreImg;
        fab_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        FavoriteImage selelctUrl = favoriteImageDao.getImageUrl(lovePreImg);
                        if (selelctUrl != null) {
                            runOnUiThread(new Runnable() {
                                @SuppressLint("UseCompatLoadingForDrawables")
                                @Override
                                public void run() {
                                    fab_like.setForeground(getDrawable(R.drawable.love));
                                    Toast.makeText(ViewActivity2.this, "Cancel successfully", Toast.LENGTH_SHORT).show();
                                }
                            });
                            new Thread(() -> favoriteImageDao.deleteUser(selelctUrl)).start();
                        }
                    }
                }).start();
            }
        });
    }




    private void initViewPaper() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<Fragment> list = new ArrayList<>();
                List<FavoriteImage> alldatas;
                alldatas = favoriteImageDao.getAllFavoriteImages();
                for (int i = recop; i <= alldatas.size() - 1; i++) {
                    FavoriteImage favoriteImage1 = alldatas.get(i);
                    list.add(PreviewFragment.newInstance(favoriteImage1.imageUrl));
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        viewPagerPreview.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
                            @NonNull
                            @Override
                            public Fragment getItem(int position) {
                                return list.get(position);
                            }

                            @Override
                            public int getCount() {
                                return list.size();
                            }
                        });
                    }
                });

            }
        }).start();

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

            }

            @Override
            public void onPageSelected(int position) {
                lovePreImg = favoriteImage.getImageUrl();

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void loadPreview(String preURl) {
        Glide.with(this)
                .asBitmap()
                .load(preURl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        WallpaperOptionsBottomSheet bottomSheet = new WallpaperOptionsBottomSheet();
                        bottomSheet.setWallpaperBitmap(resource);
                        bottomSheet.show(getSupportFragmentManager(), "wallpaper_options");
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                    }
                });
    }
    private void showMax(onActionListener listener) {

        // TODO: 2024/9/23   Ad

        if (listener != null)
            listener.onAction();

    }

    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.viewpager_preview).setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
    }
}
