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

require_relative "../task_helper"

PHP_KEYWORDS_FILE = "./lib/rouge/lexers/php/keywords.rb"

namespace :builtins do
  task :php do
    PHPBuiltins.process(PHP_KEYWORDS_FILE)
  end
end

class PHPBuiltins < BuiltinsGenerator
  PHP_DOCS_URI = "https://www.php.net/distributions/manual/php_manual_en.tar.gz"

  # TODO: [jneen] rewrite this Zip::File/TarReader and avoid shelling out
  def fetch
    files = Hash.new

    system "mkdir -p /tmp/rouge"
    Dir.chdir "/tmp/rouge" do
      system "wget -qO- #{PHP_DOCS_URI} | tar -xz"
      Dir.chdir './php-chunked-xhtml' do
        Dir.glob('./ref.*').sort.each do |f|
          files[File.basename(f)] = File.read(f)
        end
      end
    end

    files.values
  end

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

    @input.each do |file|
      file =~ %r(<title>(.*?) Functions</title>)
      name = $1

      next unless name

      file.scan %r(<a href="function\..*?\.html">([\w\\]+)</a>) do |m|
        keywords[name].push m[0]
      end
    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:php`."
    yield   "# See tasks/builtins/php.rake for more info."
    yield   ""
    yield   "module Rouge"
    yield   "  module Lexers"
    yield   "    class PHP"
    yield   "      BUILTINS = {}.tap do |b|"
    @keywords.each do |n, fs|
      yield "        b[#{n.inspect}] = Set.new #{fs.inspect}"
    end
    yield   "      end"
    yield   "    end"
    yield   "  end"
    yield   "end"
  end
end
