# frozen_string_literal: true

module UxToolkitCompatibilityHelper
  def ux_toolkit_sprite_icon(icon_name, label = nil, options = {})
    return ux_toolkit_call_sprite_icon(icon_name, label, options) if respond_to?(:sprite_icon, true)

    h(label.to_s)
  end

  def list_autofill_data_attributes
    return super if defined?(super)

    {}
  end

  def ux_toolkit_repository_type(repository)
    return '-' unless repository

    type_name = repository.class.name.to_s.split('::').last
    type_name.present? ? type_name.titleize : '-'
  end

  def ux_toolkit_repository_location_label(repository)
    location = ux_toolkit_repository_location(repository)
    return l(:label_ux_toolkit_repository_location_local) if location == :local
    return l(:label_ux_toolkit_repository_location_remote) if location == :remote

    l(:label_ux_toolkit_repository_location_unknown)
  end

  def ux_toolkit_modern_ui
    return RedmineUxToolkit::Services::ModernUi if defined?(RedmineUxToolkit::Services::ModernUi)

    service_path = File.expand_path('../../lib/redmine_ux_toolkit/services/modern_ui.rb', __dir__)
    require_dependency service_path
    load service_path unless defined?(RedmineUxToolkit::Services::ModernUi)
    RedmineUxToolkit::Services::ModernUi if defined?(RedmineUxToolkit::Services::ModernUi)
  rescue LoadError, NameError
    nil
  end

  private

  def ux_toolkit_call_sprite_icon(icon_name, label, options)
    sprite_icon(icon_name, label, options)
  rescue ArgumentError
    sprite_icon(icon_name, label, **options)
  rescue NoMethodError
    h(label.to_s)
  end

  def ux_toolkit_repository_location(repository)
    url = ux_toolkit_repository_url(repository)
    return :unknown if url.blank?
    return :local if url.match?(/\Afile:\/\//i)
    return :remote if url.match?(/\A(?:https?|svn(?:\+ssh)?|git|ssh|rsync):\/\//i)
    return :remote if url.match?(/\A[^@\s]+@[^:\s]+:.+\z/)
    return :local if url.match?(/\A(?:\/|[A-Za-z]:[\\\/])/)

    :unknown
  end

  def ux_toolkit_repository_url(repository)
    %i[root_url url].each do |method_name|
      next unless repository.respond_to?(method_name)

      value = repository.public_send(method_name).to_s
      return value if value.present?
    end

    nil
  end
end
