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.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
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.PreviewFragment2;
import com.example.wallpapermagazine.json.Info;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

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

public class ViewActivity extends AppCompatActivity {
    private FrameLayout frameLayoutBack;
    private ViewPager viewPagerPreview;
    private List<Info> info;
    private AppDatabase appDatabase;
    private WallpaperManager wallpaperManager;
    private FloatingActionButton fab_download, fab_like, fab_share;
    private String selectPreImg;
    private TextView textViewLoading;
    private FavoriteImageDao favoriteImageDao;
    private int nameop;
    private int recop;
    private static final int STORAGE_PERMISSION_CODE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_layout);
//        MaxManager.onLoadAd();
        // TODO: 2024/9/23 Ad 
        inint();
        nameop = getIntent().getIntExtra("naop", 2);
        recop = getIntent().getIntExtra("dataop", 16);
        info = WallPaperSelect.getCataName().get(nameop).getDatas();
        appDatabase = AppDatabase.getDatabase(this);
        selectPreImg = info.get(recop).getOriginal();
        wallpaperManager = WallpaperManager.getInstance(this);
        frameLayoutBack = findViewById(R.id.back);
        viewPagerPreview = findViewById(R.id.viewpager_preview);
        textViewLoading = findViewById(R.id.textview_loading);
        fab_download = findViewById(R.id.fbt_download);
        fab_like = findViewById(R.id.fbt_love);
        fab_share = findViewById(R.id.fbt_show);
        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 (selectPreImg != null) {
                            loadPreview(selectPreImg);
                        } else {
                            Toast.makeText(ViewActivity.this, "Sorry setting failed", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
        fab_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selectPreImg != null) {
                    textViewLoading.setVisibility(View.VISIBLE);
                    ImageDownloadTask downloadTask = new ImageDownloadTask(getBaseContext(), new DownloadListener() {
                        @Override
                        public void downloadResult(boolean isSuccess) {
                            textViewLoading.setVisibility(View.GONE);
                            if (isSuccess) {
                                Toast.makeText(ViewActivity.this, "Image downloaded successfully", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(ViewActivity.this, "Failed to download image", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    downloadTask.execute(selectPreImg);
                }
            }
        });
        FavoriteImage favoriteImage = new FavoriteImage();
        favoriteImage.imageUrl = selectPreImg;
        favoriteImageDao = appDatabase.favoriteImageDao();

        new Thread(new Runnable() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void run() {
                FavoriteImage favoriteImage3 = favoriteImageDao.getImageUrl(selectPreImg);
                if (favoriteImage3 != null) {
                    fab_like.setForeground(getDrawable(R.drawable.select_like));
                }
            }
        }).start();
        fab_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        FavoriteImage favoriteImage1 = favoriteImageDao.getImageUrl(selectPreImg);
                        if (favoriteImage1 == null) {
                            runOnUiThread(new Runnable() {
                                @SuppressLint("UseCompatLoadingForDrawables")
                                @Override
                                public void run() {
                                    fab_like.setForeground(getDrawable(R.drawable.select_like));
                                    Toast.makeText(ViewActivity.this, "Added successfully", Toast.LENGTH_SHORT).show();
                                }
                            });
                            favoriteImage1 = new FavoriteImage();
                            favoriteImage1.imageUrl = selectPreImg;
                            new InsertImageTask().execute(favoriteImage1);
                        } else {
                            //delete
                            FavoriteImage favoriteImage2 = favoriteImage1;
                            runOnUiThread(new Runnable() {
                                @SuppressLint("UseCompatLoadingForDrawables")
                                @Override
                                public void run() {
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            favoriteImageDao.deleteUser(favoriteImage2);
                                        }
                                    }).start();
                                    fab_like.setForeground(getDrawable(R.drawable.love));
                                    Toast.makeText(ViewActivity.this, "Cancel successfully", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });
        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, selectPreImg); // 可以添加URL文本
                startActivity(Intent.createChooser(shareIntent, "Share pictures"));
            }
        });
    }

    @SuppressLint("StaticFieldLeak")
    private class InsertImageTask extends AsyncTask<FavoriteImage, Void, Void> {
        @Override
        protected Void doInBackground(FavoriteImage... favoriteImages) {
            appDatabase.favoriteImageDao().insert(favoriteImages[0]);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

        }
    }

    private void initViewPaper() {
        List<Fragment> list = new ArrayList<>();
        List<Info> infoList = WallPaperSelect.getCataName().get(nameop).getDatas();
        for (int i = recop; i <= recop + 6; i++) {
            Info myInfo = infoList.get(i);
            list.add(PreviewFragment2.newInstance(myInfo.getOriginal()));
        }
        viewPagerPreview.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return list.get(position);
            }

            @Override
            public int getCount() {
                return list.size();
            }
        });
        viewPagerPreview.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        FavoriteImage selelctUrl = favoriteImageDao.getImageUrl(infoList.get(position).getOriginal());
                        runOnUiThread(new Runnable() {
                            @SuppressLint({"UseCompatLoadingForDrawables"})
                            @Override
                            public void run() {
                                if (selelctUrl != null) {
                                    fab_like.setForeground(getDrawable(R.drawable.select_like));
                                } else {
                                    Drawable drawable = getDrawable(R.drawable.love);
                                    fab_like.setForeground(drawable);
                                }
                            }

                        });

                    }
                }).start();
                selectPreImg = infoList.get(position).getOriginal();
            }

            @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 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);
    }

    private void showMax(onActionListener listener) {
        // TODO: 2024/9/23 Ad

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

    }
}
