module Aigu
  class EmberPodExporter < Exporter
  protected

    def build_output
      @output = build_output_from_global_translations(@input_directory, @locale)
      @output.merge! build_output_from_pods(@input_directory, @locale)

      @output
    end

    def build_output_from_global_translations(input_directory, locale)
      pattern = File.join(input_directory, '**', 'locales', locale, 'translations.*.json')

      Dir[pattern].reduce({}) do |memo, file|
        content = read_or_ignore(file, input_directory)

        return nil unless content

        root_key = file.match(/translations\.([a-z]+)\.json/)[1]
        base_key = file.gsub(/^#{input_directory}/, '').gsub(/^\//, '').gsub(/[a-z]+\/translations\.[a-z]+\.json$/, "__LOCALE__/translations.#{root_key}.json|")

        content = flattenize_hash(content, base_key)

        memo.merge! content
      end
    end

    def build_output_from_pods(input_directory, locale)
      pattern = File.join(input_directory, '**', "translations.#{locale}.json")

      Dir[pattern].reduce({}) do |memo, file|
        content = read_or_ignore(file, input_directory)

        return nil unless content

        base_key = file.gsub(/^#{input_directory}/, '').gsub(/^\//, '').gsub(/\/translations.#{locale}.json$/, '/translations.__LOCALE__.json|')

        content = flattenize_hash(content, base_key)

        memo.merge! content
      end
    end

    def write_json_file
      file_path = @output_file
      puts "Generating #{file_path}"
      FileUtils.mkdir_p(File.dirname(file_path))

      File.open(file_path, 'w+') do |file|
        file << @output.to_json
      end
    end

    def read_or_ignore(file, input_directory)
      filepath = file.gsub(/\A#{input_directory}\//, '')

      if ignored_filepath?(filepath)
        puts "Ignoring #{filepath}"
        false
      else
        puts "Processing #{filepath}"
        content = File.read(file)
        JSON.parse(content)
      end
    end

    def flattenize_hash(hash, base_key = '')
      if hash.is_a?(Hash)
        hash.reduce({}) do |memo, (key, value)|
          new_base_key = [base_key, key].join('.').gsub(/\|\.+/, '|')
          memo.merge! flattenize_hash(value, new_base_key)
        end
      else
        { base_key.gsub(/^\./, '') => hash }
      end
    end

    def ignored_filepath?(filepath)
      @ignore && @ignore.any? do |pattern|
        File.fnmatch(pattern, filepath, File::FNM_PATHNAME | File::FNM_DOTMATCH)
      end
    end
  end
end