# frozen_string_literal: true

require 'json'

module TanukiEmoji
  module Db
    # Gemojione Emoji database
    class Gemojione
      DATA_FILE = 'vendor/gemojione/index-3.3.0.json'

      def self.data_file
        File.expand_path(File.join(__dir__, '../../../', DATA_FILE))
      end

      attr_reader :data_file

      def initialize(index:, data_file: self.class.data_file)
        @data_file = data_file
        @index = index
      end

      def load!
        db = File.open(data_file, 'r:UTF-8') do |file|
          JSON.parse(file.read, symbolize_names: true)
        end

        db.each do |emoji_name, emoji_data|
          emoji = Character.new(emoji_name.to_s,
                                codepoints: emoji_data[:moji],
                                alpha_code: emoji_data[:shortname],
                                description: emoji_data[:name],
                                category: emoji_data[:category])

          emoji_data[:unicode_alternates].each do |unicode_alternates|
            codepoints = unicode_hex_to_codepoint(unicode_alternates)

            emoji.add_codepoints(codepoints)
          end

          emoji_data[:aliases].each do |alpha_code|
            emoji.add_alias(alpha_code)
          end

          emoji_data[:aliases_ascii].each do |ascii_string|
            emoji.add_ascii_alias(ascii_string)
          end

          @index.add(emoji)
        end
      end

      private

      def unicode_hex_to_codepoint(unicode)
        unicode.split('-').map { |i| i.to_i(16) }.pack('U*')
      end
    end
  end
end
