package com.wall.photography.picture.activity;


import android.app.WallpaperManager;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.ad.tradpluslibrary.TPAdManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.DecodeFormat;
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.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.wall.photography.picture.MyApp;
import com.wall.photography.picture.R;
import com.wall.photography.picture.databinding.ActivityWallapperBinding;
import com.wall.photography.picture.fragment.MyDialog;
import com.wall.photography.picture.tool.CommonUtils;
import com.wall.photography.picture.tool.ObjectBoxManager;
import com.wall.photography.picture.tool.JsonParser;
import com.wall.photography.picture.Connect.SelectType;
import com.wall.photography.picture.data_bean.Data;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function2;
import okhttp3.Call;

public class Wallpaper extends AppCompatActivity implements SelectType {

    private WeakReference<Wallpaper> weakReference;
    private Data data;
    private WallpaperManager wallpaperManager;
    private int permissionCode = 1;
    private String mSavePath;
    private String imId;
    private String fullUrl;

    private MyDialog dialogType;

    private File downloadFile;
    private Call call;
    private ActivityWallapperBinding vb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = ActivityWallapperBinding.inflate(getLayoutInflater());
        CommonUtils.initFull(this, true);
        setContentView(vb.getRoot());
        weakReference = new WeakReference<>(this);
        // 使用新的 API 替代已过时的 getSerializableExtra()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            data = getIntent().getSerializableExtra(CommonUtils.key_info, Data.class);
        } else {
            data = (Data) getIntent().getSerializableExtra(CommonUtils.key_info);
        }
        if (data == null) {
            return;
        }
        imId = data.getImId();
        mSavePath = JsonParser.INSTANCE.getSaveFilePath(this, imId);
        wallpaperManager = WallpaperManager.getInstance(this);
        initClick();
        loadDetail();
        vb.tvContent.setText(data.getDescription());
        TPAdManager.INSTANCE.showTPAD(Wallpaper.this, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                return null;
            }
        });
    }

    private void loadDetail() {
        String previewUrl400 = data.getPreviewUrl400();
        String previewUrl1080 = data.getPreviewUrl1080();
        fullUrl = data.getFullUrl();

        File file = new File(mSavePath);
        RequestOptions options = new RequestOptions()
                .format(DecodeFormat.PREFER_RGB_565);


        int[] screenWidthHeight = CommonUtils.getScreenWidthHeight(this);
        Log.d(MyApp.TAG, "--------width=" + screenWidthHeight[0] + "----height=" + screenWidthHeight[1]);
        if (file.exists()) {
            Glide.with(this)
                    .load(file)
                    .apply(options)
                    .placeholder(R.mipmap.im_placeholder)
                    .transition(DrawableTransitionOptions.withCrossFade(500))
                    .into(vb.imageviewPreview);
        } else {
            Glide.with(this)
                    .asDrawable()
                    .load(previewUrl1080)
                    .apply(options)
                    .skipMemoryCache(true)

                    .placeholder(R.mipmap.im_placeholder)
                    .thumbnail(
                            Glide.with(Wallpaper.this)
                                    .asDrawable()
                                    .load(previewUrl400)
                                    .apply(options)
                                    .placeholder(R.mipmap.im_placeholder)

                                    .centerCrop()
                    )
                    .transition(DrawableTransitionOptions.withCrossFade(500)) // 500ms 淡入效果
                    .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;
                        }
                    })
                    .centerCrop()
                    .into(vb.imageviewPreview);


        }


        boolean b = ObjectBoxManager.queryIsLike(imId);
        vb.imageFavorite.setSelected(b);

    }

    private void initClick() {
        vb.imageviewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        vb.buttonSet.setOnClickListener(v -> {

            TPAdManager.INSTANCE.showTPAD(Wallpaper.this, new Function0<Unit>() {
                @Override
                public Unit invoke() {
                    if (dialogType == null) {
                        dialogType = new MyDialog();
                        dialogType.setListener(Wallpaper.this);
                    }
                    if (!dialogType.isAdded()) {
                        dialogType.show(getSupportFragmentManager(), "");
                    }
                    return null;
                }
            });




        });
        vb.imageFavorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean selected = vb.imageFavorite.isSelected();
                vb.imageFavorite.setSelected(!selected);
                boolean selectedNew = vb.imageFavorite.isSelected();
                data.setLike(selectedNew);
                ObjectBoxManager.updateLike(data);

            }
        });
        vb.layoutDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean permission = JsonParser.INSTANCE.requestPermission(Wallpaper.this, permissionCode);
                if (!permission) {
                    return;
                }

                TPAdManager.INSTANCE.showTPAD(Wallpaper.this, new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        startSaveToAlbum();
                        return null;
                    }
                });
            }
        });
    }

    private void startSaveToAlbum() {
        showDownloadLoading(true);

        if (downloadFile != null && downloadFile.exists()) {
            Log.d(MyApp.TAG, "-----------Download 2");
            startSave(downloadFile);
            return;
        }
        Log.d(MyApp.TAG, "-----------Download 3");
        doDownload(true, true);

    }

    private void doDownload(boolean showMsg, boolean save) {
        call = JsonParser.INSTANCE.downloadFile(fullUrl, mSavePath, new Function2<Boolean, InputStream, Unit>() {
            @Override
            public Unit invoke(Boolean aBoolean, InputStream inputStream) {
                File file = new File(mSavePath);
                if (aBoolean && file.exists()) {
                    downloadFile = file;
                    if (save) {
                        startSave(downloadFile);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Wallpaper activity = weakReference.get();
                            if (activity != null && !activity.isDestroyed()) {
                                Log.d(MyApp.TAG, "-------weakReference !=null");

                            } else {
                                Log.d(MyApp.TAG, "-------weakReference null");
                            }

                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showDownloadLoading(false);
                            if (showMsg) {
                                Toast.makeText(Wallpaper.this, getString(R.string.download_fail), Toast.LENGTH_SHORT).show();
                            }

                        }
                    });

                }
                return null;
            }
        });
    }

    private void showDownloadLoading(boolean show) {
        if (show) {
            vb.pbDownload.setVisibility(View.VISIBLE);
            vb.imageDownload.setVisibility(View.GONE);
        } else {
            vb.pbDownload.setVisibility(View.GONE);
            vb.imageDownload.setVisibility(View.VISIBLE);
        }
    }

    private void showSetWallpaperLoading(boolean show) {
        Log.d(MyApp.TAG, "-----------showSetWallpaperLoading" + show);
        if (show) {
            vb.pbSet.setVisibility(View.VISIBLE);
            vb.buttonSet.setVisibility(View.GONE);
        } else {
            vb.pbSet.setVisibility(View.GONE);
            vb.buttonSet.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == permissionCode && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startSaveToAlbum();
        }
    }

    private void startSave(File file) {
        ObjectBoxManager.insertOrUpdateDownload(data);
        Uri uri = JsonParser.INSTANCE.saveToGallery(Wallpaper.this, file);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDownloadLoading(false);
                if (uri == null) {
                    Toast.makeText(Wallpaper.this, getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(Wallpaper.this, getString(R.string.save_success), Toast.LENGTH_LONG).show();
                }
                Log.d(MyApp.TAG, "--------path=" + file.getAbsolutePath() + "---uri=" + uri);
            }
        });


    }

    @Override
    public void onSelectType(int type) {

        showSetWallpaperLoading(true);
        if (downloadFile != null && downloadFile.exists()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.d(MyApp.TAG, "--------downloadFile=" + downloadFile.exists());
                    setWallpaper(downloadFile, type);
                }
            }).start();
        }

        else {
            call = JsonParser.INSTANCE.downloadFile(fullUrl, mSavePath, new Function2<Boolean, InputStream, Unit>() {
                @Override
                public Unit invoke(Boolean aBoolean, InputStream inputStream) {
                    Log.d(MyApp.TAG, "--------downloadFile=" + Thread.currentThread().getName());
                    File file = new File(mSavePath);
                    if (aBoolean && file.exists()) {
                        downloadFile = file;
                        setWallpaper(downloadFile, type);
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showSetWallpaperLoading(false);
                                Toast.makeText(Wallpaper.this, getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                    return null;
                }
            });
        }


    }


    private void setWallpaper(File file, int type) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            switch (type) {
                case MyDialog.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 MyDialog.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 MyDialog.type_both:
                    wallpaperManager.setStream(fileInputStream);
                    break;
            }
            deleteCacheFile();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSetWallpaperLoading(false);
                    Toast.makeText(Wallpaper.this, getString(R.string.set_success), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception exception) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSetWallpaperLoading(false);
                    Toast.makeText(Wallpaper.this, getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void deleteCacheFile() {
        if (downloadFile != null && downloadFile.exists()) {
            boolean delete = downloadFile.delete();
            Log.d(MyApp.TAG, "--------delete=" + delete);
        }
    }

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