# frozen_string_literal: true

require_relative '../../ext/localizationlinter/localizationlinter'

module Danger
  #  Verify consistency over your project localizable files (localizable.strings and Localizable.stringdict)
  #  It uses Swiftgen to generate a localizables output per target and language and compare the output with
  #  a reference language one.
  #  The comparison ensure:
  #    - missing keys
  #    - additional keys
  #    - wrong parameters in string format
  #
  # @example Verify my project localizables consistency
  #          localizationlinter.lint
  #
  # @see  https://github.com/fabernovel/danger-localizationlinter
  # @tags iOS, Localization

  class DangerLocalizationlinter < Plugin
    # Keep or clean derived data after execution
    # @return  [void]
    attr_accessor :clean_after_execution

    # Print inline or as markdown
    # @return  [void]
    attr_accessor :inline_mode

    # Print execution logs
    # @return  [void]
    attr_accessor :verbose

    # Path to language configuration yml, defining main language per target
    # example:
    #```yml
    # My_target: en
    # My_other_target: fr
    #```
    # Default value is `Configuration/Defaults/all_target_main_language.yml`
    # If no file is provided, the default language for each target is `en`
    # @return  [void]
    attr_accessor :language_configuration_path

    # Path to swift gen, default value is Pods/SwiftGen/bin/swiftgen
    # @return  [void]
    attr_accessor :swift_gen_path

    # Path to derived data, default value is localization_linter_derived_data
    # @return  [void]
    attr_accessor :derived_data_path

    # Path to derived data, default value is Resources
    # @return  [void]
    attr_accessor :resource_path

    # Path to xcode project, default is taking the first project in root folder
    # @return  [void]
    attr_accessor :project_path

    # Verify the localizable files integrity over the project
    # @return  [void]
    # rubocop:disable Metrics/MethodLength
    def lint
      differences = linter.find_differences
      if differences.empty?
        linter.log "Localization Linter finished with no error"
      elsif inline_mode
        differences.each do |issue|
          warn(
            issue[:message],
            file: issue[:filename],
            line: issue[:line]
          )
        end
      else
        message = differences.map do |difference|
          "#{difference[:filename]}:#{difference[:line]} #{difference[:message]}"
        end
        markdown "Localization Linter errors:\n#{message.join("\n")}"
      end
    end
    # rubocop:enable Metrics/MethodLength

    # Returns the object in charge of verification
    # @return  [LocalizationLinter]
    def linter
      LocalizationLinter.new(
        @verbose,
        @clean_after_execution,
        @language_configuration_path,
        @swift_gen_path,
        @derived_data_path,
        @resource_path,
        @project_path
      )
    end
  end
end