package com.ninty.nativee.io;

import com.ninty.nativee.INativeMethod;
import com.ninty.nativee.NaMethodManager;
import com.ninty.runtime.NiFrame;
import com.ninty.runtime.heap.NiClass;
import com.ninty.runtime.heap.NiClassLoader;
import com.ninty.runtime.heap.NiObject;
import com.ninty.runtime.heap.NiString;

import java.io.File;

/**
 * Created by ninty on 2018/10/24
 */
public class NaUnixFileSystem {
    private final static String className = "java/io/UnixFileSystem";

    public static void init() {
        NaMethodManager.register(className, "initIDs", "()V",
                new initIDs());
        NaMethodManager.register(className, "getBooleanAttributes0", "(Ljava/io/File;)I",
                new getBooleanAttributes0());
        NaMethodManager.register(className, "list", "(Ljava/io/File;)[Ljava/lang/String;",
                new list());
    }

    public static class initIDs implements INativeMethod {
        @Override
        public void invoke(NiFrame frame) {
        }
    }

    public static class getBooleanAttributes0 implements INativeMethod {
        @Override
        public void invoke(NiFrame frame) {
            frame.getOperandStack().pushInt(0);
        }
    }

    public static class list implements INativeMethod {
        @Override
        public void invoke(NiFrame frame) {
            NiObject fileObj = frame.getLocalVars().getRef(1);
            String path = NiString.getString(fileObj.getFieldRef("path", "Ljava/lang/String;"));
            File file = new File(path);
            String[] files = file.list();
            if(files == null){
                frame.getOperandStack().pushRef(null);
                return;
            }
            NiClassLoader loader = frame.getMethod().getClz().getLoader();
            NiClass arrStr = loader.loadClass("[java/lang/String;");
            NiObject filesObj = arrStr.newArray(files.length);
            for (int i = 0; i < files.length; i++) {
                filesObj.aobject()[i] = NiString.newString(loader, files[i]);
            }
            frame.getOperandStack().pushRef(filesObj);
        }
    }
}

@@ -854,22 +854,163 @@
 ist());%0A
+        NaMethodManager.register(className, %22canonicalize0%22, %22(Ljava/lang/String;)Ljava/lang/String;%22,%0A                new canonicalize0());%0A
     %7D%0A
-
 %0A    pub
@@ -1714,16 +1714,17 @@
       if
+ 
 (files =
@@ -1730,16 +1730,17 @@
 == null)
+ 
 %7B%0A      
@@ -2170,32 +2170,32 @@
 ;%0A            %7D%0A
-
             fram
@@ -2248,11 +2248,266 @@
  %7D%0A    %7D
+%0A%0A    public static class canonicalize0 implements INativeMethod %7B%0A        @Override%0A        public void invoke(NiFrame frame) %7B%0A            NiObject path = frame.getLocalVars().getRef(1);%0A            frame.getOperandStack().pushRef(path);%0A        %7D%0A    %7D
 %0A%7D%0A

add native method: java.io.UnixFileSystem.canonicalize0(Ljava/lang/String;)Ljava/lang/String;