package com.house.wallpapers.myactivity;


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 androidx.core.view.WindowCompat;

import com.ad.toponlibrary.AdManager;
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.house.wallpapers.App;
import com.house.wallpapers.adapter.OnSelecttype;
import com.house.wallpapers.databinding.ActivityMyWallapperBinding;
import com.house.wallpapers.mybean.Data;
import com.house.wallpapers.myfragment.Mydialog;
import com.house.wallpapers.mytool.Comutils;
import com.house.wallpapers.mytool.ObectManager;
import com.house.wallpapers.R;
import com.house.wallpapers.mytool.JsonData;

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 MyWallpaperActivity extends AppCompatActivity implements OnSelecttype {

    private WeakReference<MyWallpaperActivity> 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 ActivityMyWallapperBinding vb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = ActivityMyWallapperBinding.inflate(getLayoutInflater());
        Comutils.initFull(this, true);
        setContentView(vb.getRoot());
        AdManager.loadAllAd();
        weakReference = new WeakReference<>(this);
        data = (Data) getIntent().getSerializableExtra(Comutils.key_info);
        if (data == null) {
            return;
        }
        imId = data.getImId();
        mSavePath = JsonData.INSTANCE.getSaveFilePath(this, imId);
        wallpaperManager = WallpaperManager.getInstance(this);
        initClick();
        loadDetail();
        vb.tvContent.setText(data.getDescription());
    }

    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[] screenWidthHeight = Comutils.getScreenWidthHeight(this);
        Log.d(App.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)

                    .placeholder(R.mipmap.im_placeholder)
                    .thumbnail(
                            Glide.with(MyWallpaperActivity.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(App.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 = ObectManager.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 (dialogType == null) {
                dialogType = new Mydialog();
                dialogType.setListener(MyWallpaperActivity.this);
            }
            if (!dialogType.isAdded()) {
                dialogType.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();
                data.setLike(selectedNew);
                ObectManager.updateLike(data);

            }
        });
        vb.layoutDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean permission = JsonData.INSTANCE.requestPermission(MyWallpaperActivity.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(App.TAG, "-----------Download 2");
            startSave(downloadFile);
            return;
        }
        Log.d(App.TAG, "-----------Download 3");
        doDownload(true, true);

    }

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

                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showDownloadLoading(false);
                            if (showMsg) {
                                Toast.makeText(MyWallpaperActivity.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(App.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) {
        ObectManager.insertOrUpdateDownload(data);
        Uri uri = JsonData.INSTANCE.saveToGallery(MyWallpaperActivity.this, file);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDownloadLoading(false);
                if (uri == null) {
                    Toast.makeText(MyWallpaperActivity.this, getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
                } else {
//                    deleteCacheFile();
                    Toast.makeText(MyWallpaperActivity.this, getString(R.string.save_success), Toast.LENGTH_LONG).show();
                }
                Log.d(App.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(App.TAG, "--------downloadFile=" + downloadFile.exists());
                    setWallpaper(downloadFile, type);
                }
            }).start();
        }
//        else if (fullDrawable != null) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    File file = new File(CommonHelper.saveDrawableToFile(fullDrawable, mSavePath));
//                    setWallpaper(file, type);
//                }
//            }).start();
//        }
        else {
            call = JsonData.INSTANCE.downloadFile(fullUrl, mSavePath, new Function2<Boolean, InputStream, Unit>() {
                @Override
                public Unit invoke(Boolean aBoolean, InputStream inputStream) {
                    Log.d(App.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(MyWallpaperActivity.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(MyWallpaperActivity.this, getString(R.string.set_success), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception exception) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSetWallpaperLoading(false);
                    Toast.makeText(MyWallpaperActivity.this, getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

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

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