package eu.midnightdust.yaytris.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/*
 NightJson v0.1 by Martin Prokoph
 Extremely lightweight (and incomplete) JSON library
 Concept inspired by GSON
 */
public class NightJson {
    private static final String KEY_PATTERN = "\"(-?[0-9a-zA-Z]*)\":";
    Class<?> jsonClass;
    String fileLocation;

    public NightJson(Class<?> jsonClass, String fileLocation) {
        this.jsonClass = jsonClass;
        this.fileLocation = fileLocation;
    }

    public void writeJson() {
        if (fileLocation == null) return;
        try {
            FileWriter jsonFile = new FileWriter(fileLocation);

            jsonFile.write("{\n");
            Iterator<Field> it = Arrays.stream(jsonClass.getFields()).iterator();
            while (it.hasNext()) {
                Field field = it.next();
                jsonFile.write("\t");
                if (field.getType() == Comment.class) {
                    jsonFile.write(String.format("// %s\n", ((Comment) field.get(null)).commentString));
                    continue;
                }
                jsonFile.write(String.format(field.getType() == String.class || field.getType().isEnum() ? "\"%s\": \"%s\"" : "\"%s\": %s", field.getName(), field.get(null)));
                jsonFile.write(it.hasNext() ? ",\n" : "\n");
            }
            jsonFile.write("}");
            jsonFile.close();
        } catch (IOException | IllegalAccessException e) {
            System.out.println("Oh no! An Error occurred whilst writing the JSON file :(");
            e.fillInStackTrace();
        }
    }

    public void readJson() {
        if (fileLocation == null) return;
        try {
            File file = new File(fileLocation);
            if (!file.exists()) {
                writeJson();
                return;
            }

            Scanner jsonFile = new Scanner(file);
            Map<String, String> jsonKeyValuePairs = new HashMap<>();
            AtomicReference<String> lastKey = new AtomicReference<>();
            jsonFile.forEachRemaining(s -> {
                if (!s.matches("[{}]") && !s.matches("//+")) {
                    if (s.matches(KEY_PATTERN)) {
                        lastKey.set(s.replaceAll("([\":])", ""));
                        jsonKeyValuePairs.put(lastKey.get(), "");
                    }
                    else jsonKeyValuePairs.put(lastKey.get(), (jsonKeyValuePairs.get(
                            lastKey.get()).isEmpty() ? "" : jsonKeyValuePairs.get(lastKey.get()) + " "
                    ) + s.replaceAll("([\",])", ""));
                }
            });

            for (String key : jsonKeyValuePairs.keySet()) {
                String currentString = jsonKeyValuePairs.get(key);
                //System.out.printf("Key: %s Value: %s%n", key, currentString);
                Field field;
                try { field = jsonClass.getField(key);
                } catch (NoSuchFieldException e) {continue;}

                field.set(field, stringToObj(field, currentString));
            }
            jsonFile.close();
        } catch (IOException | IllegalAccessException | NoSuchElementException e) {
            System.out.println("Oh no! An Error occurred whilst reading the JSON file :(");
            e.fillInStackTrace();
        }
    }

    private Object stringToObj(Field field, String currentString) {
        switch (field.getType().getName()) {
            case "byte": return Byte.parseByte(currentString);
            case "int": return Integer.parseInt(currentString);
            case "long": return Long.parseLong(currentString);
            case "float": return Float.parseFloat(currentString);
            case "double": return Double.parseDouble(currentString);
            case "boolean": return Boolean.parseBoolean(currentString);
        }
        if (field.getType().isEnum()) return Arrays.stream(field.getType().getEnumConstants())
                .filter(enumConstant -> Objects.equals(enumConstant.toString(), currentString)).findFirst().orElseThrow();
        else return currentString;
    }

    public static class Comment {
        final String commentString;
        public Comment(String commentString) {
            this.commentString = commentString;
        }
    }
}
