package com.haven.wallpapers.activity;

import android.annotation.SuppressLint;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
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 com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.haven.wallpapers.R;
import com.haven.wallpapers.Utils.MyValue;
import com.haven.wallpapers.MyApp;
import com.haven.wallpapers.listener.OnDownloadListener;
import com.haven.wallpapers.listener.OnSelectTypeListener;
import com.haven.wallpapers.Utils.DownloadTask;
import com.haven.wallpapers.Utils.Save;
import com.haven.wallpapers.fragment.DialogSelectType;
import com.haven.wallpapers.jsonbean.Data;
import com.haven.wallpapers.room.AppDatabase;
import com.haven.wallpapers.room.LikeDao;
import com.haven.wallpapers.topon.AdManager;
import com.haven.wallpapers.topon.onActionListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ViewActivity extends AppCompatActivity implements OnSelectTypeListener, OnDownloadListener {
    private ImageView imagePreview;
    private String resourceImgUrl;
    private ImageView BackimageView;
    private CardView setBtn;
    private FrameLayout share;
    private FrameLayout download;
    private ImageView collect;
    private TextView textViewLoading;
    private WallpaperManager wallpaperManager;
    private LikeDao dao;


    private Data data;
    private String importurl;
    private DownloadTask downloadTask;
    private ProgressBar process;
    private DialogSelectType dialogSelectType;

    private Drawable fullDrawable;
    private File downloadFile;
    private String saveFilePath;


    //-1 保存到相册
    private String Type = "-1";
    private ExecutorService executorServiceLike;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        AdManager.loadAllAd();
        setContentView(R.layout.activity_view);
        wallpaperManager = WallpaperManager.getInstance(this);
        imagePreview = findViewById(R.id.preview);
        BackimageView = findViewById(R.id.imageview_back);
        setBtn = 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);
        FrameLayout likeLayout = findViewById(R.id.collection_layout);

        //初始化db
        initDb();


        data = (Data) getIntent().getSerializableExtra(MyValue.key_data);
        importurl = (String) getIntent().getSerializableExtra(MyValue.key_Import);
        downloadTask = new DownloadTask(this, this);

        //判断数据源
        if (importurl != null) {
            saveFilePath = Save.getSaveFilePath("import");
            download.setVisibility(View.GONE);
            likeLayout.setVisibility(View.GONE);
            resourceImgUrl = importurl;
            loadImport(importurl);
        } else if (data != null) {
            saveFilePath = Save.getSaveFilePath(data.getImId());
            downloadFile = new File(saveFilePath);
            resourceImgUrl = data.getPreviewUrl1080();
            loadPreview();
            judge();
        }

        BackimageView.setOnClickListener(v -> {

            AdManager.showTopOn(ViewActivity.this, new onActionListener() {
                @Override
                public void onAction() {
                    finish();
                }
            });

        });

        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AdManager.showTopOn(ViewActivity.this, new onActionListener() {
                    @Override
                    public void onAction() {
                        process.setVisibility(View.VISIBLE);
                        downloadTask.execute(resourceImgUrl, "-1");
                    }
                });
            }
        });

        setBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdManager.showTopOn(ViewActivity.this, new onActionListener() {
                    @Override
                    public void onAction() {
                        if (dialogSelectType == null) {
                            dialogSelectType = new DialogSelectType();
                            dialogSelectType.setListener(ViewActivity.this);
                        }
                        if (!dialogSelectType.isAdded()) {
                            dialogSelectType.show(getSupportFragmentManager(), "");
                        }
                    }
                });

            }
        });

        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, resourceImgUrl);
                startActivity(intent);
            }
        });

        collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                collect.setSelected(!collect.isSelected());
                executorServiceLike = Executors.newSingleThreadExecutor();
                executorServiceLike.submit(new Runnable() {
                    @Override
                    public void run() {
                        if (collect.isSelected()) {
                            dao.insertTask(data);
                        } else {
                            dao.deleteTaskByUrl(data.getImId());
                        }
                    }
                });

            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        AdManager.showTopOn(ViewActivity.this, new onActionListener() {
            @Override
            public void onAction() {

            }
        });
    }

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

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

    private void judge() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (dao.getTaskByUrl(data.getImId()) != null) {
                    collect.setSelected(true);
                }
            }
        }).start();
    }

    private void loadPreview() {
        Glide.with(this)
                .load(data.getPreviewUrl1080())
                .thumbnail(
                        Glide.with(this)
                                .load(data.getPreviewUrl400())
                                .centerCrop()

                )
                .transition(DrawableTransitionOptions.withCrossFade(500)) // 500ms 淡入效果
                .centerCrop()
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                        Log.d(MyApp.TAG, "-----------onLoadFailed e" + e.getMessage());
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                        fullDrawable = resource;
                        return false;
                    }
                })
                .into(imagePreview);


    }

    private void loadImport(String resourceImgUrl) {
        Glide.with(this)
                .load(resourceImgUrl)
                .transition(DrawableTransitionOptions.withCrossFade(500)) // 500ms 淡入效果
                .centerCrop()
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                        Log.d(MyApp.TAG, "-----------onLoadFailed e" + e.getMessage());
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                        fullDrawable = resource;
                        return false;
                    }
                })
                .into(imagePreview);
    }

    @Override
    public void onSelectType(int type) {
        textViewLoading.setVisibility(View.VISIBLE);
        if (downloadFile != null && downloadFile.exists()) {
            setWallpaper(downloadFile, type);
        } else if (fullDrawable != null) {
            File file = new File(Save.saveDrawableToFile(fullDrawable, saveFilePath));
            setWallpaper(file, type);
        } else {
            downloadTask.execute(resourceImgUrl, "" + type);
        }
    }


    private void setWallpaper(File file, int type) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    switch (type) {
                        case DialogSelectType.type_home:
                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                                wallpaperManager.setStream(fileInputStream);
                            } else {
                                wallpaperManager.setStream(
                                        fileInputStream,
                                        null,
                                        true,
                                        WallpaperManager.FLAG_SYSTEM
                                );
                            }
                            break;
                        case DialogSelectType.type_lock:
                            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                                wallpaperManager.setStream(fileInputStream);
                            } else {
                                wallpaperManager.setStream(
                                        fileInputStream,
                                        null,
                                        true,
                                        WallpaperManager.FLAG_LOCK
                                );
                            }
                            break;
                        case DialogSelectType.type_both:
                            wallpaperManager.setStream(fileInputStream);
                            break;
                    }

                    textViewLoading.setVisibility(View.GONE);
                    Toast.makeText(ViewActivity.this, getString(R.string.set_success), Toast.LENGTH_SHORT).show();
                } catch (Exception exception) {
                    textViewLoading.setVisibility(View.GONE);
                    Toast.makeText(ViewActivity.this, getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onDownloadResult(boolean saveGalleryOk, InputStream inputStream, String type) {
        if (type.equals("-1")) {
            boolean b = Save.writeFile(inputStream, saveFilePath);
            Log.e("--------------", "saveToGallery" + downloadFile.exists());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    process.setVisibility(View.GONE);
                    if (saveGalleryOk) {
                        Toast.makeText(ViewActivity.this, "Image downloaded successfully", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ViewActivity.this, "Failed to download image", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            boolean b = Save.writeFile(inputStream, saveFilePath);
            if (b) {
                setWallpaper(downloadFile, Integer.parseInt(type));
            } else {
                textViewLoading.setVisibility(View.GONE);
                Toast.makeText(ViewActivity.this, getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
            }

        }


    }
}
