package org.bdware.sc.boundry;

import org.bdware.sc.engine.YJSClassLoader;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import java.util.zip.ZipInputStream;
public class Resources {
    private final ZipFile zf;
    YJSClassLoader loader;

    public Resources(ZipFile zf, YJSClassLoader loader) {
        this.zf = zf;
        this.loader = loader;
    }

    public InputStream loadAsInputStream(String path) {
        try {
            ZipEntry entry = zf.getEntry(path);
            if (entry == null)
                return null;
            return zf.getInputStream(entry);
        } catch (Exception ignored) {

        }
        return null;
    }

    public Scanner loadAsScanner(String path) {
        try {
            ZipEntry entry = zf.getEntry(path);
            if (entry == null)
                return null;
            return new Scanner(zf.getInputStream(entry));
        } catch (Exception ignored) {

        }
        return null;
    }

    public String loadAsString(String path) {
        try {
            InputStream sc = loadAsInputStream(path);
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            for (int k = 0; (k = sc.read(buff)) > 0; ) {
                bo.write(buff, 0, k);
            }
            return new String(bo.toByteArray());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public List<?> testloadAsScanner(String path) {
        BufferedReader reader;
        List<String> fileList = new ArrayList<>();
        try {
            ZipEntry entry = zf.getEntry(path);
            if (entry == null)
                return null;
            reader = new BufferedReader(new InputStreamReader(zf.getInputStream(entry), StandardCharsets.UTF_8));
            String line = null;
            while ((line = reader.readLine()) != null) {
                fileList.add(line);
                // System.out.println(line);
            }
            return fileList;
            // return new ArrayList<>();
        } catch (Exception ignored) {

        }
        return null;
    }

    public String unzipToDir(String path) {
        ZipEntry entry = zf.getEntry(path);
        try {
            return loader.unzipLibrary(zf.getInputStream(entry), entry.getName().replaceAll(".*/", ""));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
