using Gee;

public class PhpToValaGeneratorWriter : Object {
    public static string indent_string (string indent_unit, int level) {
        var output = new StringBuilder ();
        for (int i = 0; i < level; i++) {
            output.append (indent_unit);
        }
        return output.str;
    }

    public static void append_indented_line (string indent_unit, StringBuilder output, int level, string line) {
        output.append (indent_string (indent_unit, level));
        output.append (line);
        output.append ("\n");
    }

    public static int append_generated_block (string indent_unit, StringBuilder output, int base_level, string generated_block, int initial_relative_level = 0) {
        int relative_level = initial_relative_level;
        foreach (string raw_line in generated_block.split ("\n")) {
            string line = raw_line.strip ();
            if (line == "") {
                output.append ("\n");
                continue;
            }

            bool starts_with_close = line.has_prefix ("}");
            int line_relative_level = relative_level;
            if (starts_with_close && line_relative_level > 0) {
                line_relative_level--;
            }

            append_indented_line (indent_unit, output, base_level + line_relative_level, line);

            int opens = count_char (line, '{');
            int closes = count_char (line, '}');
            if (starts_with_close && closes > 0) {
                closes--;
            }
            relative_level = line_relative_level + opens - closes;
            if (relative_level < 0) {
                relative_level = 0;
            }
        }
        return relative_level;
    }

    public static int count_char (string value, char needle) {
        int count = 0;
        for (int i = 0; i < value.length; i++) {
            if (value[i] == needle) {
                count++;
            }
        }
        return count;
    }

}
