require 'spec_helper'

describe MaxMindRelease do

  include UsesTempFiles

  GEOISP_124 = 'geoisp_124.csv'

  in_directory_with_file(GEOISP_124)

  before(:all) do
    @original_storage = MaxMindReleaseUploader.storage = :fog
  end

  after(:all) do
    MaxMindReleaseUploader.storage = @original_storage
  end

  let(:zipfile) {fake_geo_124_zip(File.new(GEOISP_124))}
  let(:release) {FactoryGirl.create(:max_mind_release)}

  before(:each) do
    content_for_file('abc')

    Dir.mkdir(APP_CONFIG.max_mind_working_dir) unless Dir.exists?(APP_CONFIG.max_mind_working_dir)
  end

  it "unzip" do
    result = release.unzip(APP_CONFIG.max_mind_working_dir, zipfile.path)
    result.include?('GeoIPISP.csv').should be_true
    output = result['GeoIPISP.csv']
    File.exists?(output).should be_true
    IO.read(output).should == 'abc'
  end

  it "downloads", aws: true do
    uploader = MaxMindReleaseUploader.new(release, :geo_ip_124_url)
    zipfile.open
    uploader.store!(zipfile) # uploads the file to s3
    release.save!
    release[:geo_ip_124_url].should == File.join(release.store_dir, 'geo_ip_124_url.zip')
    release[:geo_ip_124_md5].should == Digest::MD5.file(zipfile).hexdigest
    release[:geo_ip_124_size].should == zipfile.size

    downloaded_filename = release.download(release.dated_working_dir, :geo_ip_124_url, release[:geo_ip_124_md5])

    Digest::MD5.file(downloaded_filename ).hexdigest.should == Digest::MD5.file(zipfile).hexdigest
  end

  describe "import" do
    it "succeeds" do
      release.touch
      dataset = dataset_to_tmp_files
      release.import_to_database(dataset[:geo_ip_124_files], dataset[:geo_ip_134_files], dataset[:iso3166], dataset[:region_codes])
      release.imported.should be_true
      release.imported_at.should_not be_nil
    end
  end

end