package com.phone.wall.paper.view;


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.toponlibrary.AdManager;
import com.ad.toponlibrary.onActionListener;
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.phone.wall.paper.R;
import com.phone.wall.paper.WallpaperApp;
import com.phone.wall.paper.data.DataBean;
import com.phone.wall.paper.databinding.UiSetWallBinding;
import com.phone.wall.paper.listener.OnType;
import com.phone.wall.paper.tools.JsonData;
import com.phone.wall.paper.tools.RoomManager;
import com.phone.wall.paper.tools.Utils;

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 SetWall extends AppCompatActivity implements OnType {

    private WeakReference<SetWall> weakReference;
    private DataBean dataBean;
    private WallpaperManager wallpaperManager;


    private UiSetWallBinding vb;


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

    private SelectWallpaperType selectWallpaperType;

    private File downloadFile;
    private Call call;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = UiSetWallBinding.inflate(getLayoutInflater());
        Utils.initFull(this, true);
        setContentView(vb.getRoot());
        weakReference = new WeakReference<>(this);
        dataBean = (DataBean) getIntent().getSerializableExtra(Utils.key_info);
        AdManager.loadAllAd();
        if (dataBean == null) {
            return;
        }
        imId = dataBean.getImId();
        mSavePath = JsonData.INSTANCE.getSaveFilePath(this, imId);
        wallpaperManager = WallpaperManager.getInstance(this);
        initClick();
        loadDetail();
        vb.tvContent.setText(dataBean.getDescription());

        AdManager.showTopOn(this, new onActionListener() {
            @Override
            public void onAction() {

            }
        });
    }

    private void loadDetail() {
        String previewUrl400 = dataBean.getPreviewUrl400();
        String previewUrl1080 = dataBean.getPreviewUrl1080();

        fullUrl = dataBean.getFullUrl();

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


        int[] screenWidthHeight = Utils.getScreenWidthHeight(this);
        Log.d(WallpaperApp.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(SetWall.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(WallpaperApp.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 = RoomManager.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 -> {

            AdManager.showTopOn(SetWall.this, new onActionListener() {
                @Override
                public void onAction() {
                    if (selectWallpaperType == null) {
                        selectWallpaperType = new SelectWallpaperType();
                        selectWallpaperType.setListener(SetWall.this);
                    }
                    if (!selectWallpaperType.isAdded()) {
                        selectWallpaperType.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();
                dataBean.setLike(selectedNew);
                RoomManager.updateLike(dataBean);

            }
        });
        vb.layoutDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean permission = JsonData.INSTANCE.requestPermission(SetWall.this, permissionCode);
                if (!permission) {
                    return;
                }
                AdManager.showTopOn(SetWall.this, new onActionListener() {
                    @Override
                    public void onAction() {
                        startSaveToAlbum();
                    }
                });



            }
        });
    }

    private void startSaveToAlbum() {
        showDownloadLoading(true);

        if (downloadFile != null && downloadFile.exists()) {
            Log.d(WallpaperApp.TAG, "-----------Download 2");
            startSave(downloadFile);
            return;
        }
        Log.d(WallpaperApp.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() {
                            SetWall activity = weakReference.get();
                            if (activity != null && !activity.isDestroyed()) {
                                Log.d(WallpaperApp.TAG, "-------weakReference !=null");
//                                Glide.with(activity)
//                                        .asDrawable()
//                                        .load(downloadFile)
//                                        .into(vb.imageviewPreview);
                            } else {
                                Log.d(WallpaperApp.TAG, "-------weakReference null");
                            }

                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showDownloadLoading(false);
                            if (showMsg) {
                                Toast.makeText(SetWall.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(WallpaperApp.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) {
        RoomManager.insertOrUpdateDownload(dataBean);
        Uri uri = JsonData.INSTANCE.saveToGallery(SetWall.this, file);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showDownloadLoading(false);
                if (uri == null) {
                    Toast.makeText(SetWall.this, getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
                } else {
//                    deleteCacheFile();
                    Toast.makeText(SetWall.this, getString(R.string.save_success), Toast.LENGTH_SHORT).show();
                }
                Log.d(WallpaperApp.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(WallpaperApp.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(WallpaperApp.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(SetWall.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 SelectWallpaperType.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 SelectWallpaperType.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 SelectWallpaperType.type_both:
                    wallpaperManager.setStream(fileInputStream);
                    break;
            }
            deleteCacheFile();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSetWallpaperLoading(false);
                    Toast.makeText(SetWall.this, getString(R.string.set_success), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception exception) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSetWallpaperLoading(false);
                    Toast.makeText(SetWall.this, getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

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

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