package com.structurizr.dsl;

final class ModelItemParser extends AbstractParser {

    private final static int TAGS_INDEX = 1;

    private final static int URL_INDEX = 1;

    private final static int PROPERTY_NAME_INDEX = 0;
    private final static int PROPERTY_VALUE_INDEX = 1;

    private final static int PERSPECTIVE_NAME_INDEX = 0;
    private final static int PERSPECTIVE_DESCRIPTION_INDEX = 1;

    void parseTags(ModelItemDslContext context, Tokens tokens) {
        // tags <tags> [tags]
        if (!tokens.includes(TAGS_INDEX)) {
            throw new RuntimeException("Expected: tags <tags> [tags]");
        }

        for (int i = TAGS_INDEX; i < tokens.size(); i++) {
            String tags = tokens.get(i);
            context.getModelItem().addTags(tags.split(","));
        }
    }

    void parseUrl(ModelItemDslContext context, Tokens tokens) {
        // url <url>
        if (tokens.hasMoreThan(URL_INDEX)) {
            throw new RuntimeException("Too many tokens, expected: url <url>");
        }

        if (!tokens.includes(URL_INDEX)) {
            throw new RuntimeException("Expected: url <url>");
        }

        String url = tokens.get(URL_INDEX);
        context.getModelItem().setUrl(url);
    }

    void parseProperty(ModelItemPropertiesDslContext context, Tokens tokens) {
        // <name> <value>

        if (tokens.hasMoreThan(PROPERTY_VALUE_INDEX)) {
            throw new RuntimeException("Too many tokens, expected: <name> <value>");
        }

        if (tokens.size() != 2) {
            throw new RuntimeException("Expected: <name> <value>");
        }

        String name = tokens.get(PROPERTY_NAME_INDEX);
        String value = tokens.get(PROPERTY_VALUE_INDEX);

        context.getModelItem().addProperty(name, value);
    }

    void parsePerspective(ModelItemPerspectivesDslContext context, Tokens tokens) {
        // <name> <description>

        if (tokens.hasMoreThan(PERSPECTIVE_DESCRIPTION_INDEX)) {
            throw new RuntimeException("Too many tokens, expected: <name> <description>");
        }

        if (tokens.size() != 2) {
            throw new RuntimeException("Expected: <name> <description>");
        }

        String name = tokens.get(PERSPECTIVE_NAME_INDEX);
        String value = tokens.get(PERSPECTIVE_DESCRIPTION_INDEX);

        context.getModelItem().addPerspective(name, value);
    }

}