package com.apps.chillscreen.uiView;

import android.app.WallpaperManager;
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.appcompat.app.AppCompatActivity;

import com.ad.toponlibrary.AdManager;
import com.ad.toponlibrary.onActionListener;
import com.apps.chillscreen.R;
import com.apps.chillscreen.bean.Picture;
import com.apps.chillscreen.databinding.ActivityExtendInfoBinding;
import com.apps.chillscreen.listener.ShowFragmentListener;
import com.apps.chillscreen.tool.PictureManager;
import com.apps.chillscreen.tool.DownloadUtils;
import com.apps.chillscreen.tool.JsonConvert;
import com.apps.chillscreen.tool.OpenUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;
import java.io.FileInputStream;

import okhttp3.Call;

public class ExtendedInfoActivity extends AppCompatActivity implements ShowFragmentListener {
    ActivityExtendInfoBinding binding;
    private final int permissionCode = 1;
    public static final String pictureKey = "picture";
    private Picture picture;
    private File downloadFile;
    private String fullUrl;
    private String mSavePath;
    private Call call;
    private SetPaperFragment setPaperFragment;
    private WallpaperManager wallpaperManager;
    private boolean isSetting = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityExtendInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
        AdManager.loadAllAd();
        AdManager.showTopOn(this, new onActionListener() {
            @Override
            public void onAction() {

            }
        });
    }

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

    private void init() {
        picture = (Picture) getIntent().getSerializableExtra(pictureKey);
        if (picture == null) return;
        fullUrl = picture.getFullUrl();
        mSavePath = JsonConvert.INSTANCE.getSaveFilePath(this, picture.getImId());
        wallpaperManager = WallpaperManager.getInstance(this);
        Glide.with(this)
                .load(picture.getPreviewUrl1080())
                .apply(new RequestOptions()
                        .format(DecodeFormat.PREFER_RGB_565))
                .skipMemoryCache(true)
                .thumbnail(
                        Glide.with(this)
                                .load(picture.getPreviewUrl400())
                                .apply(new RequestOptions()
                                        .format(DecodeFormat.PREFER_RGB_565)
                                        .centerCrop()
                                )
                )
                .into(binding.imageviewPreview);
        binding.imageBack.setOnClickListener(v -> finish());
        binding.tvContent.setText(picture.getDescription());
        binding.imageFavorite.setOnClickListener(v -> setCollectStatus());
        binding.imageDownload.setOnClickListener(v -> AdManager.showTopOn(ExtendedInfoActivity.this, new onActionListener() {
            @Override
            public void onAction() {
                startDownLoad();
            }
        })
        );
        binding.layoutSet.setOnClickListener(v -> AdManager.showTopOn(ExtendedInfoActivity.this, new onActionListener() {
            @Override
            public void onAction() {
                showSetDialog();
            }
        }));
        boolean b = PictureManager.queryIsLike(picture.getImId());
        binding.imageFavorite.setSelected(b);
    }

    private void setCollectStatus() {
        boolean like = picture.isLike();
        picture.setLike(!like);
        PictureManager.updateCollect(picture);
        binding.imageFavorite.setSelected(!like);
    }

    private void startDownLoad() {
        boolean b = OpenUtil.requestPermission(this, permissionCode);
        if (!b) return;
        showDownloadLoading(true);
        if (downloadFile != null && downloadFile.exists()) {
            save(downloadFile);
            return;
        }
        getFilePath();
    }

    private void save(File file) {
        Uri uri = OpenUtil.saveToGallery(this, file);
        PictureManager.insertOrUpdateDownload(picture);
        runOnUiThread(() -> {
            showDownloadLoading(false);
            if (uri == null) {
                Toast.makeText(ExtendedInfoActivity.this, getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ExtendedInfoActivity.this, getString(R.string.save_success), Toast.LENGTH_SHORT).show();
            }
            Log.d("YYYYYY", "--------path=" + file.getAbsolutePath() + "---uri=" + uri);
        });
    }

    private void getFilePath() {
        call = DownloadUtils.downloadFile(fullUrl, mSavePath, (isSuccess, inputStream) -> {
            File file = new File(mSavePath);
            if (file.exists() && isSuccess) {
                downloadFile = file;
                save(file);
            } else {
                runOnUiThread(() -> {
                    showDownloadLoading(false);
                    Toast.makeText(ExtendedInfoActivity.this, getString(R.string.download_fail), Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void showSetDialog() {
        if (isSetting) return;
        if (setPaperFragment == null) {
            setPaperFragment = new SetPaperFragment();
            setPaperFragment.setListener(ExtendedInfoActivity.this);
        }
        if (!setPaperFragment.isAdded()) {
            setPaperFragment.show(getSupportFragmentManager(), "");
        }
    }

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

    private void showSetWallpaperLoading(boolean show) {
        Log.d("YYYYYY", "-----------showSetWallpaperLoading" + show);
        if (show) {
            isSetting = true;
            binding.pbSet.setVisibility(View.VISIBLE);
            binding.txApply.setVisibility(View.GONE);
            binding.buttonSet.setVisibility(View.GONE);

        } else {
            isSetting = false;
            binding.pbSet.setVisibility(View.GONE);
            binding.txApply.setVisibility(View.VISIBLE);
            binding.buttonSet.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onSelectType(int type) {
        showSetWallpaperLoading(true);
        if (downloadFile != null && downloadFile.exists()) {
            new Thread(() -> {
                Log.d("YYYYYY", "skip download and set");
                setWallPaper(downloadFile, type);
            }).start();
        } else {
            call = DownloadUtils.downloadFile(fullUrl, mSavePath, (isSuccess, inputStream) -> {
                File file = new File(mSavePath);
                if (file.exists() && isSuccess) {
                    downloadFile = file;
                    setWallPaper(downloadFile, type);
                } else {
                    runOnUiThread(() -> {
                        showSetWallpaperLoading(false);
                        Toast.makeText(ExtendedInfoActivity.this, getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
                    });
                }
            });
        }
    }

    private void setWallPaper(File file, int type) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            switch (type) {
                case SetPaperFragment.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 SetPaperFragment.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 SetPaperFragment.type_both:
                    wallpaperManager.setStream(fileInputStream);
                    break;
            }
            runOnUiThread(() -> {
                showSetWallpaperLoading(false);
                Toast.makeText(ExtendedInfoActivity.this,
                        getString(R.string.set_success),
                        Toast.LENGTH_SHORT).show();
            });
        } catch (Exception e) {
            runOnUiThread(() -> {
                showSetWallpaperLoading(false);
                Toast.makeText(ExtendedInfoActivity.this,
                        getString(R.string.set_fail),
                        Toast.LENGTH_SHORT).show();
            });
        }
    }

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