package com.hd.wallpaper.free.walls.ui;

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.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.bitmap.CircleCrop;
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.hd.wallpaper.free.walls.MyWallpaper;
import com.hd.wallpaper.free.walls.R;
import com.hd.wallpaper.free.walls.databinding.ActivitySetBinding;
import com.hd.wallpaper.free.walls.db.DbManager;
import com.hd.wallpaper.free.walls.json.Data;
import com.hd.wallpaper.free.walls.mylistener.TypeListener;
import com.hd.wallpaper.free.walls.utils.CommonKt;
import com.hd.wallpaper.free.walls.utils.CommonUtils;

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

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

public class ActivitySet extends AppCompatActivity implements TypeListener {

    private WeakReference<ActivitySet> weakReference;
    private Data data;
    private WallpaperManager wallpaperManager;


    private ActivitySetBinding vb;

    private Drawable fullDrawable;
    private int permissionCode = 1;
    private String mSavePath;
    private String imId;
    private String fullUrl;

    private DialogSetType dialogSetType;

    private File downloadFile;
    private Call call;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = ActivitySetBinding.inflate(getLayoutInflater());
        CommonUtils.initFull(this, true);
        setContentView(vb.getRoot());
        weakReference = new WeakReference<>(this);
        data = (Data) getIntent().getSerializableExtra(CommonUtils.key_info);
        if (data == null) {
            return;
        }
        imId = data.getImId();
        mSavePath = CommonKt.INSTANCE.getSaveFilePath(this, imId);
        wallpaperManager = WallpaperManager.getInstance(this);
        initClick();
        loadDetail();
    }

    private void loadDetail() {
        String previewUrl400 = data.getPreviewUrl400();
        String previewUrl1080 = data.getPreviewUrl1080();
        String previewUrl200 = data.getPreviewUrl200();
        String authorHeader = data.getAuthorHeader();
        String authorName = data.getAuthorName();
        String authorHtml = data.getAuthorHtml();
        fullUrl = data.getFullUrl();

        File file = new File(mSavePath);
        RequestOptions options = new RequestOptions()
                .format(DecodeFormat.PREFER_RGB_565);
        int width = vb.imageviewPreview.getWidth();
        int height = vb.imageviewPreview.getHeight();

        int[] screenWidthHeight = CommonUtils.getScreenWidthHeight(this);
        Log.d(MyWallpaper.TAG,"--------width="+screenWidthHeight[0]+"----height="+screenWidthHeight[1]);
        if (file.exists()) {
            Glide.with(this)
                    .load(file)
                    .apply(options)
                    .placeholder(R.mipmap.im_placeholder)
//                    .override(screenWidthHeight[0], screenWidthHeight[1])
                    .transition(DrawableTransitionOptions.withCrossFade(500))
                    .into(vb.imageviewPreview);
        } else {
            Glide.with(this)
                    .asDrawable()
                    .load(previewUrl1080)
                    .apply(options)
                    .skipMemoryCache(true)
//                    .override(screenWidthHeight[0], screenWidthHeight[1])
                    .placeholder(R.mipmap.im_placeholder)
                    .thumbnail(
                            Glide.with(ActivitySet.this)
                                    .asDrawable()
                                    .load(previewUrl400)
                                    .apply(options)
                                    .placeholder(R.mipmap.im_placeholder)
//                                    .override(screenWidthHeight[0], screenWidthHeight[1])
                                    .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(MyWallpaper.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);
//            doDownload(false, false);


        }


        Glide.with(this)
                .load(authorHeader)
                .transform(new CircleCrop())
                .into(vb.imageHeader);
        vb.textName.setText(authorName);
        vb.textHtml.setText(authorHtml);

        boolean b = DbManager.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 -> {
            if (dialogSetType == null) {
                dialogSetType = new DialogSetType();
                dialogSetType.setListener(ActivitySet.this);
            }
            if (!dialogSetType.isAdded()) {
                dialogSetType.show(getSupportFragmentManager(), "");
            }


        });
        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();
                if (selectedNew) {
                    DbManager.insertOrUpdateLike(data);
                } else {
                    DbManager.deleteLike(data);
                }
            }
        });
        vb.layoutDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean permission = CommonKt.INSTANCE.requestPermission(ActivitySet.this, permissionCode);
                if (!permission) {
                    return;
                }
                startSaveToAlbum();


            }
        });
    }

    private void startSaveToAlbum() {
        showDownloadLoading(true);
//        File file = new File(mSavePath);
//        if (file.exists()) {
//            Log.d(MyWallpaper.TAG, "-----------Download 1");
//            startSave(file);
//            return;
//        }
        if (downloadFile != null && downloadFile.exists()) {
            Log.d(MyWallpaper.TAG, "-----------Download 2");
            startSave(downloadFile);
            return;
        }
        Log.d(MyWallpaper.TAG, "-----------Download 3");
        doDownload(true, true);

    }

    private void doDownload(boolean showMsg, boolean save) {
        call = CommonKt.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() {
                            ActivitySet activity = weakReference.get();
                            if (activity != null && !activity.isDestroyed()) {
                                Log.d(MyWallpaper.TAG, "-------weakReference !=null");
//                                Glide.with(activity)
//                                        .asDrawable()
//                                        .load(downloadFile)
//                                        .into(vb.imageviewPreview);
                            } else {
                                Log.d(MyWallpaper.TAG, "-------weakReference null");
                            }

                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showDownloadLoading(false);
                            if (showMsg) {
                                Toast.makeText(ActivitySet.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(MyWallpaper.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) {
        DbManager.insertOrUpdateDownload(data);
        Uri uri = CommonKt.INSTANCE.saveToGallery(ActivitySet.this, file);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDownloadLoading(false);
                if (uri == null) {
                    Toast.makeText(ActivitySet.this, getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
                } else {
                    deleteCacheFile();
                    Toast.makeText(ActivitySet.this, getString(R.string.save_success), Toast.LENGTH_SHORT).show();
                }
                Log.d(MyWallpaper.TAG, "--------path=" + file.getAbsolutePath() + "---uri=" + uri);
            }
        });


    }

    @Override
    public void onSelectType(int type) {
        Log.d(MyWallpaper.TAG, "--------onSelectType=" + Thread.currentThread().getName());
        showSetWallpaperLoading(true);
        if (downloadFile != null) {
           new Thread(new Runnable() {
               @Override
               public void run() {
                   setWallpaper(downloadFile, type);
               }
           }).start();
        } else if (fullDrawable != null) {
           new Thread(new Runnable() {
               @Override
               public void run() {
                   File  file = new File(CommonUtils.saveDrawableToFile(fullDrawable, mSavePath));
                   setWallpaper(file, type);
               }
           }).start();
        } else {
            call = CommonKt.INSTANCE.downloadFile(fullUrl, mSavePath, new Function2<Boolean, InputStream, Unit>() {
                @Override
                public Unit invoke(Boolean aBoolean, InputStream inputStream) {
                    Log.d(MyWallpaper.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(ActivitySet.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 DialogSetType.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 DialogSetType.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 DialogSetType.type_both:
                    wallpaperManager.setStream(fileInputStream);
                    break;
            }
            deleteCacheFile();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSetWallpaperLoading(false);
                    Toast.makeText(ActivitySet.this, getString(R.string.set_success), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception exception) {
         runOnUiThread(new Runnable() {
             @Override
             public void run() {
                 showSetWallpaperLoading(false);
                 Toast.makeText(ActivitySet.this, getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
             }
         });
        }
    }

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

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