package com.keyborad.theme.trendyborad.trendyutils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

import com.keyborad.theme.trendyborad.TrendyApp;
import com.keyborad.theme.trendyborad.trendycallback.TrendySetKeyboardCallback;

import net.sf.sevenzipjbinding.ArchiveFormat;
import net.sf.sevenzipjbinding.IArchiveOpenCallback;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.impl.RandomAccessFileOutStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TrendyDealZipFile {

    public static void startDownloadZip(String zipPath, TrendySetKeyboardCallback callback) {
        OkHttpClient clientZip = new OkHttpClient().newBuilder().
                connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS).build();
        Request.Builder builder = new Request.Builder();
        Request request = builder.get().url(zipPath).build();

        clientZip.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.OnApplySkinListener(null);
            }

            @Override
            public void onResponse(Call call, Response response) {

                InputStream inputStream = response.body().byteStream();
                long l = response.body().contentLength();
                MediaType mediaType = response.body().contentType();

                saveZipFile(inputStream, getServiceZipName(zipPath), callback);

            }
        });
    }


    public static String getServiceZipName(String zipPath) {
        String pointStr = "/";
        int lastIndexOf = zipPath.lastIndexOf(pointStr);
        String zipName = zipPath.substring(lastIndexOf + pointStr.length());


        return zipName;
    }

    private static String getunZipFolderName(String zipPath) {
        String pointStr = ".";
        int lastIndexOf = zipPath.lastIndexOf(pointStr);
        String zipName = zipPath.substring(0, lastIndexOf);


        return zipName;
    }

    private static void saveZipFile(InputStream inputStream, String zipFileName, TrendySetKeyboardCallback callback) {
        File zipfFile = new File(TrendyApp.trendyAppInstance.getFilesDir(), zipFileName);

        Log.d("-------------------","-------zipFileName="+zipFileName);
        byte[] bytes = new byte[4096];
        int readLength = 0;
        InputStream is = inputStream;
        FileOutputStream fileOs = null;
        try {
            fileOs = new FileOutputStream(zipfFile);

            while ((readLength = is.read(bytes)) != -1) {
                fileOs.write(bytes, 0, readLength);
            }
            fileOs.flush();

        } catch (Exception exception) {

        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fileOs != null) {
                    fileOs.close();
                }
            } catch (IOException ioException) {

            }
            un7ZZipFile(zipfFile, callback);
        }

    }

    public static String getUnzipPath(String zipName){
        String folderName = getunZipFolderName(zipName);
        String replace = folderName.replace(".", "");
        return TrendyApp.trendyAppInstance.getFilesDir().getPath() + "/" + replace;
    }

    private static void un7ZZipFile(File saveZipFile, TrendySetKeyboardCallback callback) {
        List<File> fileList = new ArrayList<>();

        String unzipFolderPath = getUnzipPath(saveZipFile.getName());

        try {
            RandomAccessFileInStream inStream = new RandomAccessFileInStream(new RandomAccessFile(saveZipFile, "r"));
            IInArchive open = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP, inStream, new IArchiveOpenCallback() {
                @Override
                public void setTotal(Long files, Long bytes) {

                }

                @Override
                public void setCompleted(Long files, Long bytes) {

                }
            });


            ISimpleInArchive simple = open.getSimpleInterface();
            for (ISimpleInArchiveItem archiveItem : simple.getArchiveItems()) {
                RandomAccessFileOutStream outStream = null;
                try {
                    File itemFile;
                    if (archiveItem.isFolder()) {
                        File itemFolder = new File(unzipFolderPath, archiveItem.getPath());
                        boolean mkdirs = itemFolder.mkdirs();
                        continue;
                    } else {
                        itemFile = new File(unzipFolderPath, archiveItem.getPath());
                        if (!itemFile.getParentFile().exists()) {
                            boolean mkdirs = itemFile.getParentFile().mkdirs();
                        }
                    }
                    outStream = new RandomAccessFileOutStream(new RandomAccessFile(itemFile, "rw"));
                    archiveItem.extractSlow(outStream);
                    fileList.add(itemFile);
                } finally {
                    if (outStream != null) {
                        outStream.close();
                    }
                }
            }


            inStream.close();
            open.close();

        } catch (FileNotFoundException | SevenZipException exception) {

        } catch (IOException ioException) {

        } finally {
            if (saveZipFile.exists()) {

                saveZipFile.delete();

            }
            callback.OnApplySkinListener(fileList);
        }
    }

    public static File findFirstDirectory(File dir) {
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        return file; // 返回第一个文件目录
                    }
                }
            }
        }
        return null; // 如果没有找到文件目录，则返回null
    }


    private static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        // 如果不是 BitmapDrawable，则创建一个空的 Bitmap 对象
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    // 将 Bitmap 保存到文件
    private static void saveBitmapToFile(Bitmap bitmap, File file) throws IOException {
        if(!file.exists()){
            file.createNewFile();
        }
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);  // 保存为 PNG 格式
        out.flush();
        out.close();
    }

    // 示例：将 Drawable 写入文件
    public static void saveDrawableToFile(Drawable drawable, File file) throws IOException {
        Bitmap bitmap = drawableToBitmap(drawable);
        saveBitmapToFile(bitmap, file);
    }


}
