package com.lh.wallpaper2;

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.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.lh.wallpaper2.room.TaskDao;
import com.lh.wallpaper2.room.Favorite;
import com.lh.wallpaper2.download.ImageDownloadTask;
import com.lh.wallpaper2.room.AppDatabase;
import com.lh.wallpaper2.fragment.PreviewFragment;
import com.lh.wallpaper2.json.Url;

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

public class ViewActivity extends AppCompatActivity {
    private ArrayList<Url> url;
    private int position;
    private ViewPager viewPagerPreview;
    private String selectPreImg;
    private ImageView BackimageView;
    private CardView cardView;
    private FrameLayout share;
    private FrameLayout download;
    private ImageView collect;
    private TextView textViewLoading;
    private WallpaperManager wallpaperManager;
    private TaskDao dao;
    private Favorite favorite;
    private Favorite info;
    private Url homeInfo;
    private String topInfo;
    private String importurl;
    private ImageDownloadTask downloadTask;
    private ProgressBar process;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_view);
        wallpaperManager = WallpaperManager.getInstance(this);
        viewPagerPreview = findViewById(R.id.viewpager_preview);
        BackimageView = findViewById(R.id.imageview_back);
        cardView = findViewById(R.id.cardView);
        share = findViewById(R.id.share);
        download = findViewById(R.id.download);
        collect = findViewById(R.id.collection);
        textViewLoading = findViewById(R.id.textview_loading);
        process = findViewById(R.id.progressbar);
        //初始化db
        initDb();
        topInfo = (String) getIntent().getSerializableExtra("top_info");
        importurl = (String) getIntent().getSerializableExtra("import");
        info = (Favorite) getIntent().getSerializableExtra("info");
        url = (ArrayList<Url>) getIntent().getSerializableExtra(StaticValue.key_picture);
        homeInfo = (Url) getIntent().getSerializableExtra("home_info");
        position = getIntent().getIntExtra(StaticValue.key_position, 0);
        //判断数据源
        if (info != null) {
            selectPreImg = info.getPicture();
            judge();
        }else if (importurl != null){
            download.setVisibility(View.GONE);
            selectPreImg = importurl;
            judge();
        }
        else if (homeInfo != null) {
            selectPreImg = homeInfo.getSourceUrl();
            judge();
        } else if (topInfo != null) {
            selectPreImg = topInfo;
            judge();
        } else {
            selectPreImg = url.get(position).getSourceUrl();
            judge();
        }

        //初始化壁纸
        initViewPagerPreview();
        BackimageView.setOnClickListener(v -> {
            finish();
        });

        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                process.setVisibility(View.VISIBLE);
                if (selectPreImg != null) {
                    downloadTask = new ImageDownloadTask(getBaseContext(), ViewActivity.this);
                    downloadTask.execute(selectPreImg);

                } else {
                    Toast.makeText(ViewActivity.this, "Failed to download image...", Toast.LENGTH_SHORT).show();
                }
            }
        });

        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textViewLoading.setVisibility(View.VISIBLE);
                if (selectPreImg != null) {
                    loadPreview(selectPreImg);
                } else {
                    textViewLoading.setVisibility(View.GONE);
                    Toast.makeText(ViewActivity.this, getString(R.string.set_wallpaper_fail), Toast.LENGTH_SHORT).show();
                }
            }
        });

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, selectPreImg);
                startActivity(intent);
            }
        });

        collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        if (dao.getTaskByUrl(selectPreImg) == null) {
                            Log.d("qqqqqqqqqq", "run: ");
                            favorite = new Favorite();
                            favorite.setPicture(selectPreImg);
                            dao.insertTask(favorite);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    @SuppressLint("UseCompatLoadingForDrawables")
                                    Drawable drawable = getResources().getDrawable(R.drawable.like_icon);
                                    collect.setForeground(drawable);
                                    Toast.makeText(ViewActivity.this, "Added successfully", Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else {
                            dao.deleteTaskByUrl(selectPreImg);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    @SuppressLint("UseCompatLoadingForDrawables")
                                    Drawable drawable = getResources().getDrawable(R.drawable.dislike);
                                    collect.setForeground(drawable);
                                    Toast.makeText(ViewActivity.this, "Cancel successfully", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }).start();
            }
        });
    }

    private void initDb() {
        //初始化db
        AppDatabase db = AppDatabase.getInstance(this);
        dao = db.taskDao();
    }

    private void judge() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("2323232", "run: " + selectPreImg);
                if (dao.getTaskByUrl(selectPreImg) != null) {
                    Log.d("2323232", "run: " + dao.getTaskByUrl(selectPreImg));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable = getResources().getDrawable(R.drawable.like_icon);
                            collect.setForeground(drawable);
                        }
                    });
                }
            }
        }).start();
    }

    private void loadPreview(String selectPreImg) {
        Glide.with(this)
                .asBitmap()
                .load(selectPreImg)
                .centerInside()
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        setPhoneWallpaper(resource);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        textViewLoading.setVisibility(View.GONE);
                    }
                });
    }

    private void setPhoneWallpaper(Bitmap bitmap) {
        try {
            wallpaperManager.setBitmap(bitmap);
            //finish();
            Toast.makeText(this, getString(R.string.set_wallpaper_success), Toast.LENGTH_SHORT).show();
        } catch (IOException ioException) {
            Toast.makeText(this, getString(R.string.set_wallpaper_fail), Toast.LENGTH_SHORT).show();
        }
        textViewLoading.setVisibility(View.GONE);
    }

    private void initViewPagerPreview() {
        List<Fragment> list = new ArrayList<>();
        list.add(PreviewFragment.newInstance(selectPreImg));
        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) {
                selectPreImg = url.get(position).getSourceUrl();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }
}
