module Repository::LanguagesPercentagable
  extend ActiveSupport::Concern

  def languages_precentagable
    result = Gitea::Repository::Languages::ListService.call(@owner.login,
      @repository.identifier, current_user&.gitea_token)

    @transform_language = result[:status] === :success ? hash_transform_precentagable(result[:body]) : nil
    update_project_language(@transform_language) unless @transform_language.nil?
    @transform_language
  end

  def update_project_language(language)
    return if @project.project_language.present?
    db_language = ProjectLanguage.find_or_create_by!(name: language.keys.first.downcase.upcase_first)
    @project.update_attribute(:project_language_id, db_language.id)
  rescue
    return
  end

  # hash eq:{"JavaScript": 301681522,"Ruby": 1444004,"Roff": 578781}
  def hash_transform_precentagable(hash)
    total_byte_size = hash.values.sum
    hash.transform_values { |v|
      ActionController::Base.helpers
        .number_to_percentage((v * 100.0 / total_byte_size), precision: 1)
    }.select{|k,v| v != "0.0%"}
  end
end
