package com.newapp.paperwall.uiview;

import android.app.WallpaperManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.newapp.paperwall.BaseApp;
import com.newapp.paperwall.R;
import com.newapp.paperwall.adapter.WallpaperAdapter;
import com.newapp.paperwall.databinding.FragCollectBinding;
import com.newapp.paperwall.javabean.Data;
import com.newapp.paperwall.listener.CollectListener;
import com.newapp.paperwall.listener.DialogListener;
import com.newapp.paperwall.tools.DbManager;
import com.newapp.paperwall.tools.JsonData;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.objectbox.reactive.DataSubscription;
import kotlin.Unit;
import kotlin.jvm.functions.Function2;
import okhttp3.Call;


public class CollectFragment extends Fragment implements CollectListener, DialogListener {

    private FragCollectBinding vb;
    private DataSubscription dataSubscription;
    private WallpaperAdapter wallpaperAdapter;
    private List<Data> wallPapers = new ArrayList<>();
    private int permissionCode = 1;
    private SettingDialog dialogType;
    private Map<String, File> downloadedFilesMap = new HashMap<>();
    private Call call;
    private WeakReference<FragmentActivity> weakReference;
    private Data thisData;
    private Data thisDownData;
    private String mSavePath;
    private String fullUrl;
    private String fullDownUrl;
    private WallpaperManager wallpaperManager;
    private boolean isDownloading = false;

    public CollectFragment() {

    }

    public static CollectFragment newInstance() {
        CollectFragment fragment = new CollectFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public void onResume(){
        super.onResume();
        setTransform();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        vb = FragCollectBinding.inflate(getLayoutInflater());
        vb.tvNoData.setText(getString(R.string.no_like_data));
        initList();
        wallpaperManager = WallpaperManager.getInstance(requireActivity());
        return vb.getRoot();
    }

    private void initList() {
        wallpaperAdapter = new WallpaperAdapter(requireContext(), new ArrayList<>());
        dataSubscription = DbManager.setLikeDataListener(dataList -> {
            Log.d(BaseApp.TAG, "------size = " + dataList.size());
            if (dataList.isEmpty()) {
                vb.layoutNoData.setVisibility(View.VISIBLE);
                vb.llCollect.setVisibility(View.GONE);
            } else {
                vb.layoutNoData.setVisibility(View.GONE);
                vb.llCollect.setVisibility(View.VISIBLE);
                wallpaperAdapter.setDataInfo(dataList);
                wallpaperAdapter.notifyDataSetChanged();
            }
        });
        wallpaperAdapter.setListener(this);
        vb.viewPager2.setAdapter(wallpaperAdapter);
        vb.viewPager2.setOffscreenPageLimit(1);
        setTransform();
        // 设置初始页面为中间位置
        vb.viewPager2.setCurrentItem(0);

    }

    // 设置页面变换器，用于实现中间大左右小的效果
    private void setTransform() {
        vb.viewPager2.setPageTransformer((page, position) -> {
            if (page.getWidth() == 0) return;

            float scaleFactor = 0.8f;
            float translateX = page.getWidth() * -position * (1 - scaleFactor);

            page.post(() -> {
                if (position < -1) {
                    page.setScaleX(scaleFactor);
                    page.setScaleY(scaleFactor);
                    page.setTranslationX(translateX);
                } else if (position <= 1) {
                    float scale = 1 - Math.abs(position) * (1 - scaleFactor);
                    page.setScaleX(scale);
                    page.setScaleY(scale);
                    page.setTranslationX(translateX);
                } else {
                    page.setScaleX(scaleFactor);
                    page.setScaleY(scaleFactor);
                    page.setTranslationX(translateX);
                }
            });
        });
    }

//    @Override
//    public void onItemClickAction(Data info) {
//        Intent intent = new Intent(requireContext(), DetailActivity.class);
//        intent.putExtra(CommonUtils.key_info, info);
//        startActivity(intent);
//    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isDownloading = false;
        deleteCacheFiles();
        if (dataSubscription != null) {
            dataSubscription.cancel();
        }
        if (call != null) {
            call.cancel();
        }
        Log.d(BaseApp.TAG, "------favoriteFragment-onDestroyView");
    }


    @Override
    public void onSetClick(Data data, int position) {
        thisData = data;
        fullUrl = thisData.getFullUrl();
        mSavePath = JsonData.INSTANCE.getSaveFilePath(requireActivity(), data.getImId());
        if (dialogType == null) {
            dialogType = new SettingDialog();
            dialogType.setListener(CollectFragment.this);
        }
        if (!dialogType.isAdded()) {
            dialogType.show(getChildFragmentManager(), "");
        }
    }

    @Override
    public void onDownloadClick(Data data, int position) {
        boolean permission = JsonData.INSTANCE.requestPermission(requireActivity(), permissionCode);
        if (isDownloading) {
            Toast.makeText(requireActivity(), "正在下载中，请稍候...", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!permission) {
            return;
        }
        isDownloading = true;
        thisDownData = data;
        Log.d("YYYYYYY", "position is " + position);
        Log.d("YYYYYYY", "wallpapper is " + thisDownData.getDescription());
        weakReference = new WeakReference<>(requireActivity());
        mSavePath = JsonData.INSTANCE.getSaveFilePath(requireActivity(), data.getImId());
        Log.d("YYYYYYY", "fullDownUrl is " + thisDownData.getFullUrl());
        fullDownUrl = data.getFullUrl();
        startSaveToAlbum();
    }

    @Override
    public void onRemoveClick(int position) {
        vb.viewPager2.setCurrentItem(Math.max(0, vb.viewPager2.getCurrentItem() - 1), true);
        setTransform();
        vb.viewPager2.requestLayout();
        wallpaperAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSelectType(int type) {
        vb.searchPb.setVisibility(View.VISIBLE);
        // 从 Map 中获取当前图片对应的已下载文件
        File downloadedFile = downloadedFilesMap.get(thisData.getImId());

        if (downloadedFile != null && downloadedFile.exists()) {
            new Thread(() -> {
                setWallpaper(downloadedFile, type);
            }).start();
        } else {
            // 如果未下载，则重新下载
            call = JsonData.INSTANCE.downloadFile(fullUrl, mSavePath, (aBoolean, inputStream) -> {
                if (aBoolean) {
                    File file = new File(mSavePath);
                    if (file.exists()) {
                        // 下载成功后存入 Map
                        downloadedFilesMap.put(thisData.getImId(), file);
                        setWallpaper(file, type);
                    }
                } else {
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(requireActivity(), 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 SettingDialog.type_home:
                    wallpaperManager.setStream(
                            fileInputStream,
                            null,
                            true,
                            WallpaperManager.FLAG_SYSTEM
                    );
                    break;
                case SettingDialog.type_lock:
                    wallpaperManager.setStream(
                            fileInputStream,
                            null,
                            true,
                            WallpaperManager.FLAG_LOCK
                    );
                    break;
                case SettingDialog.type_both:
                    wallpaperManager.setStream(fileInputStream);
                    break;
            }
            deleteCacheFiles();
            requireActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    vb.searchPb.setVisibility(View.GONE);
                    Toast.makeText(requireActivity(), getString(R.string.set_success), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception exception) {
            requireActivity().runOnUiThread(() -> {
                vb.searchPb.setVisibility(View.GONE);
                Toast.makeText(requireActivity(), getString(R.string.set_fail), Toast.LENGTH_SHORT).show();
            });
        }
    }

    private void deleteCacheFiles() {
        for (File file : downloadedFilesMap.values()) {
            if (file != null && file.exists()) {
                file.delete();
            }
        }
        downloadedFilesMap.clear(); // 清空 Map
    }

    private void startSaveToAlbum() {
        vb.searchPb.setVisibility(View.VISIBLE);
        // 从 Map 中获取当前图片的已下载文件
        File downloadedFile = downloadedFilesMap.get(thisDownData.getImId());
        Log.d("YYYYYY", "download" + downloadedFile);
        if (downloadedFile != null && downloadedFile.exists()) {
            startSave(downloadedFile);
        } else {
            doDownload(true, true);
        }
    }

    private void startSave(File file) {
        DbManager.insertOrUpdateDownload(thisDownData);
        Uri uri = JsonData.INSTANCE.saveToGallery(requireActivity(), file);
        requireActivity().runOnUiThread(() -> {
            vb.searchPb.setVisibility(View.GONE);
            if (uri == null) {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireActivity(), getString(R.string.save_fail), Toast.LENGTH_SHORT).show();
                });
            } else {
//                    deleteCacheFile();
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireActivity(), getString(R.string.save_success), Toast.LENGTH_SHORT).show();
                    requestTransform();
                });
            }
            Log.d(BaseApp.TAG, "--------path=" + file.getAbsolutePath() + "---uri=" + uri);
        });


    }
    private void requestTransform() {
        vb.viewPager2.post(() -> {
            int currentItem = vb.viewPager2.getCurrentItem();
            vb.viewPager2.setCurrentItem(currentItem, false); // 无动画跳转当前页
            setTransform(); // 重新应用变换
        });
    }

    private void doDownload(boolean showMsg, boolean save) {
        call = JsonData.INSTANCE.downloadFile(fullDownUrl, mSavePath, (aBoolean, inputStream) -> {
            isDownloading = false;
            if (aBoolean) {
                File file = new File(mSavePath);
                if (file.exists()) {
                    // 存入 Map
                    downloadedFilesMap.put(thisDownData.getImId(), file);
                    if (save) {
                        startSave(file);
                    }
                }
            } else {
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireActivity(), getString(R.string.download_fail), Toast.LENGTH_SHORT).show();
                    vb.searchPb.setVisibility(View.GONE);
                    requestTransform();
                });
            }
            return null;
        });
    }

}