package xyz.ignatz.antlr.aidl.recognizer;

import java.util.*;

import xyz.ignatz.utils.MapToJson;

public class AidlToJsonListener extends AidlBaseListener
{
    String name;
    String type;
    ArrayList<String> imports = new ArrayList<>();

    ArrayList<Map<String, Object>> statements = new ArrayList<>();

    public String getName() {
        return name;
    }

    public String toJson() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("type", type);
        map.put("imports", imports);
        map.put("statements", statements);
        MapToJson mapToJson = new MapToJson(map);
        return mapToJson.toJson();
    }

    @Override
    public void enterAidl(AidlParser.AidlContext ctx) {
        if (ctx.parcelableStatement() != null) {
            name = ctx.parcelableStatement().id().getText();
            type = "parcelable";
        } else {
            name = ctx.interfaceStatement().id().getText();
            type = "interface";
            for (AidlParser.ImportStatementContext i : ctx.importStatement()) {
                imports.add(i.path().getText());
            }
        }
    }

    @Override
    public void enterMethodStatement(AidlParser.MethodStatementContext ctx) {
        Map<String, Object> statement = new HashMap<>();
        statement.put("type", "method");
        statement.put("id", ctx.id().getText());
        statement.put("return", ctx.methodReturnType().getText());
        if (ctx.paramList() != null) {
            ArrayList<Map<String, Object>> params = new ArrayList<>();
            for (AidlParser.ParamContext i : ctx.paramList().param()) {
                Map<String, Object> param = new HashMap<>();
                if (i.paramTag() != null) {
                    param.put("tag", i.paramTag().getText());
                }
                param.put("type", i.paramType().getText());
                param.put("tid", i.paramType().tid);
                param.put("id", i.id().getText());
                params.add(param);
            }
            statement.put("params", params);
        }
        statements.add(statement);
    }

    @Override
    public void enterConstStatement(AidlParser.ConstStatementContext ctx) {
        Map<String, Object> statement = new HashMap<>();
        statement.put("type", "const");
        statement.put("id", ctx.id().getText());
        if (ctx.INT() != null) {
            statement.put("value", Integer.getInteger(ctx.INTEGER().getText()));
        } else {
            String str = ctx.LITERALSTRING().getText();
            statement.put("value", str.substring(1, str.length()-1));
        }
        statements.add(statement);
    }
}