$LOAD_PATH << 'lib'

require 'open-uri'  # allows to load URLs using open()
require 'deb_importer'
require 'test_helper'
require 'pp'

include DebImporter

class PackagesHelperTest < ActionView::TestCase

  test "should detect the proper order of package versions" do
    assert(DebImporter::Version.new('2') > DebImporter::Version.new('1'))
    assert(DebImporter::Version.new('1.0') > DebImporter::Version.new('0.9'))
    assert(DebImporter::Version.new('2:1') > DebImporter::Version.new('1:2'))
    assert(DebImporter::Version.new('1.0c') > DebImporter::Version.new('1.0aa'))
    assert(DebImporter::Version.new('1.0.1') > DebImporter::Version.new('1.0.0.1'))
    assert(DebImporter::Version.new('1.0.0') > DebImporter::Version.new('1.0c'))
    assert(DebImporter::Version.new('1.0') > DebImporter::Version.new('1.0~pre'))
  end

  test "should split version files into epoch, upstream and revision" do
    v = DebImporter::Version.new('1.0~git20170104-1')
    assert_equal v.epoch, '0'
    assert_equal v.upstream, '1.0~git20170104'
    assert_equal v.revision, '1'

    v = DebImporter::Version.new('0~20161219-1')
    assert_equal v.epoch, '0'
    assert_equal v.upstream, '0~20161219'
    assert_equal v.revision, '1'

    v = DebImporter::Version.new('17:2.0.0~git20161130.1.e60d0d5+dfsg1-1')
    assert_equal v.epoch, '17'
    assert_equal v.upstream, '2.0.0~git20161130.1.e60d0d5+dfsg1'
    assert_equal v.revision, '1'

    v = DebImporter::Version.new('42')
    assert_equal v.epoch, '0'
    assert_equal v.upstream, '42'
    assert_nil v.revision

    v = DebImporter::Version.new('100:9a_b~cdef')
    assert_equal v.epoch, '100'
    assert_equal v.upstream, '9a_b~cdef'
    assert_nil v.revision
  end

  test "should be able to parse local Debian repository test files" do
    Rails.logger = Logger.new(STDOUT)
    # Rails.logger.level = Logger::ERROR
    # Rails.logger.level = Logger::INFO
    Rails.logger.level = Logger::DEBUG

    # Load information about test repository from environments/test.rb
    repositories = Rails.configuration.package_sources

    Rails.logger.info "Test parsing local DEB-style repository"

    repository = repositories.first
    release = DebImporter::Release.new(repository[:url])
    assert_equal release.components, 'main restricted universe multiverse'

    # Packages enumerator must be restarted to start from position 1
    packages = release.packages('main', 'amd64')
    assert_instance_of Enumerator, packages
    first_package = packages.first

    assert_equal 'account-plugin-aim', first_package[:Package]

    # Packages enumerator must be restarted to start from position 1
    packages = release.packages('main', 'amd64')
    assert_equal 5, packages.count

    # Get information from translation file
    i18n = release.i18n('main', 'en')
    assert_match /^Real-time strategy game of ancient warfare\n0 A\.D\./, i18n.first[:'Description-en']
  end # test
end # class
