# -*- coding: utf-8 -*- #
# frozen_string_literal: true

require_relative "../task_helper"

LASSO_KEYWORDS_FILE = "./lib/rouge/lexers/lasso/keywords.rb"

namespace :builtins do
  task :lasso do
    LassoGenerator.process(LASSO_KEYWORDS_FILE)
  end
end

class LassoGenerator < BuiltinsGenerator
  LASSO_SYNTAX_URI = "https://raw.githubusercontent.com/LassoSoft/Lasso-HTML.mode/master/Contents/Resources/SyntaxDefinition.xml"

  def fetch
    URI.open(LASSO_SYNTAX_URI) { |f| f.read }
  end

  def parse
    groups = {"Types" => :types,
              "Traits" => :traits,
              "Lasso 8 Tags" => :builtins,
              "Unbound Methods" => :builtins,
              "Keywords" => :keywords,
              "Error Keywords" => :exceptions}

    keywords = Hash.new { |h,k| h[k] = Array.new }

    @input.scan(%r[<keywords id="(.*?)" .*?>(.*?)</keywords>]m) do |m|
      next unless groups.keys.include? m[0]

      values = m[1].split(/\s*<\/?string>\s*/).
                    reject { |v| v.match(/^\s*$/) }.
                    map { |v| v.strip.downcase }

      keywords[groups[m[0]]].concat values
    end

    keywords.transform_values { |v| v.sort.uniq }
  end

  def generate
    yield   "# -*- coding: utf-8 -*- #"
    yield   "# frozen_string_literal: true"
    yield   ""
    yield   "# DO NOT EDIT"
    yield   "# This file is automatically generated by `rake builtins:lasso`."
    yield   "# See tasks/builtins/lasso.rake for more info."
    yield   ""
    yield   "module Rouge"
    yield   "  module Lexers"
    yield   "    class Lasso"
    yield   "      KEYWORDS = {}.tap do |h|"
    @keywords.each do |key, value|
      yield "        h[#{key.inspect}] = Set.new #{value.inspect}"
    end
    yield   "      end"
    yield   "    end"
    yield   "  end"
    yield   "end"
  end
end
