package com.key.vibekeyboard.utils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.key.vibekeyboard.R;
import com.key.vibekeyboard.viewmodel.callbacks.UnzipCallback;

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

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class unzipUtils {

    public static void unzipFile(Context context, File resource, UnzipCallback callback) throws IOException {
        if (!resource.exists()) {
            Toast.makeText(context, context.getString(R.string.error_decompression_file_missing), Toast.LENGTH_SHORT).show();
        } else {
            String itemFilePath = "";

            File externalDir = context.getExternalFilesDir(null);
            if (externalDir == null) {
                externalDir = context.getFilesDir();
            }

            String extractPath = new File(externalDir, "ExtractedFiles").getAbsolutePath();

            RandomAccessFile accessFile = new RandomAccessFile(resource, "r");
            RandomAccessFileInStream inStream = new RandomAccessFileInStream(accessFile);
            IInArchive iInArchive = SevenZip.openInArchive(ArchiveFormat.SEVEN_ZIP, inStream);
            ISimpleInArchiveItem[] archiveItems = iInArchive.getSimpleInterface().getArchiveItems();

            for (ISimpleInArchiveItem simple : archiveItems) {
                File file = new File(extractPath, simple.getPath());
                if (!simple.isFolder()) {
                    RandomAccessFileOutStream outStream = new RandomAccessFileOutStream(new RandomAccessFile(file, "rw"));
                    simple.extractSlow(outStream);
                    itemFilePath = file.getPath();
                    Log.d("--------", "path:  " + itemFilePath);
                } else {
                    boolean mkdirs = file.mkdirs();
                }
            }

            inStream.close();
            iInArchive.close();

            int res = itemFilePath.indexOf("res");
            String substring = itemFilePath.substring(0, res + 3);
            Log.d("--------", "substring:  " + substring);

            callback.onUnzipCall(true, substring);
        }
    }

}
