#!/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(ms_image_id: l.to_i).first
        begin
          if !i.nil?
            hires_path = File.dirname(i.hires_location)
            hires_file_name = File.basename(i.hires_location)
            medium_path = File.dirname(i.medium_location)
            thumb_path = File.dirname(i.thumb_location)
            Dir.foreach("#{Rails.root}/public/#{hires_path}") do |f|
              file_name = File.basename(f)
              if file_name.gsub(/[^a-zA-Z0-9]/, '_') == hires_file_name
                file_name_regex = file_name.gsub(/[^a-zA-Z0-9\._]/, '_' )
                begin
                   FileUtils.mv "#{Rails.root}/public/#{hires_path}/#{file_name}", "#{Rails.root}/public/#{hires_path}/#{file_name_regex}", :force => true
                rescue Exception => error
                   log.write("#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - [ERROR] : #{error}\n")
                end
                FileUtils.mv("#{Rails.root}/public/#{i.medium_location}","#{Rails.root}/public/#{medium_path}/#{file_name_regex}")
                FileUtils.mv("#{Rails.root}/public/#{i.thumb_location}","#{Rails.root}/public/#{thumb_path}/#{file_name_regex}")
                i.update(original_filename: file_name, file_name: file_name_regex, thumb_location: thumb_path+'/'+file_name_regex, medium_location: medium_path+'/'+file_name_regex, hires_location: hires_path+'/'+file_name_regex)
                #i.save
                log.write("#{i.ms_image_id} - #{i.file_name} updated\n")
                ic = ic + 1
              end
            end
          else
            log.write("#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - [ERROR] : #{l} not found\n")
          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