package com.ninty.nativee.lang;

import com.ninty.nativee.INativeMethod;
import com.ninty.nativee.NaMethodManager;
import com.ninty.runtime.LocalVars;
import com.ninty.runtime.NiFrame;
import com.ninty.runtime.heap.NiObject;

/**
 * Created by ninty on 2017/8/19.
 */
public class NaSystem {

    private final static String className = "java/lang/System";

    public static void init() {
        NaMethodManager.register(className, "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V", new arraycopy());
        NaMethodManager.register(className, "initProperties", "(Ljava/util/Properties;)Ljava/util/Properties;", new initProperties());
        NaMethodManager.register(className, "nanoTime", "()J", new nanoTime());
    }

    public static class arraycopy implements INativeMethod {
        @Override
        public void invoke(NiFrame frame) {
            LocalVars localVars = frame.getLocalVars();
            NiObject src = localVars.getRef(0);
            int srcPos = localVars.getInt(1);
            NiObject desc = localVars.getRef(2);
            int descPos = localVars.getInt(3);
            int length = localVars.getInt(4);
            if (!src.getClz().isArray() || !desc.getClz().isArray()) {
                throw new ArrayStoreException();
            }
            System.arraycopy(src.getArrayDatas(), srcPos, desc.getArrayDatas(), descPos, length);
        }
    }

    public static class initProperties implements INativeMethod {
        @Override
        public void invoke(NiFrame frame) {
            NiObject ref = frame.getLocalVars().getRef(0);
            frame.getOperandStack().pushRef(ref);
        }
    }

    public static class nanoTime implements INativeMethod {
        @Override
        public void invoke(NiFrame frame) {
            frame.getOperandStack().pushLong(System.nanoTime());
        }
    }
}

@@ -178,16 +178,55 @@
 iFrame;%0A
+import com.ninty.runtime.heap.NiClass;%0A
 import c
@@ -754,24 +754,121 @@
 anoTime());%0A
+        NaMethodManager.register(className, %22setIn0%22, %22(Ljava/io/InputStream;)V%22, new setIn0());%0A
     %7D%0A%0A    p
@@ -1982,11 +1982,330 @@
  %7D%0A    %7D
+%0A%0A    public static class setIn0 implements INativeMethod %7B%0A        @Override%0A        public void invoke(NiFrame frame) %7B%0A            NiObject self = frame.getLocalVars().getThis();%0A            NiClass clz = frame.getMethod().getClz();%0A            clz.setStaticRef(%22out%22, %22Ljava/io/PrintStream;%22, self);%0A        %7D%0A    %7D
 %0A%7D%0A

add native method: java.lang.System.setIn0(Ljava/io/InputStream;)V