#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/../config/environment.rb'
require 'optparse'
require 'optparse/time'

OptionParser.new do |opts|
  opts.banner = "Usage: search_images listing.txt"

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end

end.parse!

if ARGV.blank?
  puts 'error : no arguments, use -h or --help for help'
  exit
end

ic = 0
ARGV.collect do |f|
  if File.zero?(f)
    puts 'Fichier vide!'
  else
    File.open(f) do |listing|
      log = File.open("#{File.basename(f,".*")}.log","a+")
      listing.each_line do |l|
        l.strip!
        i = Image.where("file_name = #{l.dump}").first
        begin
          if !i.nil?
            log.write("#{i.ms_image_id};#{i.file_name};#{i.medium_location}\n")
            ic = ic + 1
          end unless l.blank?
        rescue Exception => error
          log.write("#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - [ERROR] : #{error}\n")
        end
      end
      log.close
      puts "Search completed : #{ic} file(s) found"
      if  File.zero?("#{File.basename(f,".*")}.log")
        File.delete("#{File.basename(f,".*")}.log")
      else
        puts "Files list : #{File.basename(f,".*")}.log"
      end
    end
  end
end