#!/usr/bin/env ruby

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

options = {}

OptionParser.new do |opts|
  opts.banner = "Usage: update_images [options]  listing.txt"

  opts.on("-f images_field", "--field", "(default ms_image_id) name of the images table field used to find them") do |l|
    options[:field] = l
  end

  opts.on("-p provider_string_key", "--provider", String, "files will be erased only for this provider string key") do |l|
    options[:provider] = l
  end

  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

options[:field] = 'ms_image_id' if options[:field].blank?
if options[:provider]
  prov = Provider.find_by_string_key(options[:provider])
  if prov.nil?
    puts "error : provider with string_key '#{options[:provider]}' not found"
    exit
  else
    search_str_complement = " AND provider_id = #{prov.id}"
    top_prov = RefreshProvider.find_by(provider_id: prov.id)
    top_prov_nb_updated = UpdatedListProvider.joins(:refresh_provider).where(refresh_providers:{provider_id: prov.id},created_at: Time.now().beginning_of_month..Time.now().end_of_month).sum(:nb_photos)
    top_quota = top_prov.blank? ? 0 : top_prov.total_update - top_prov_nb_updated
  end
end

ic = 0
tc = 0

ARGV.collect do |f|
  if File.zero?(f)
    puts 'Fichier vide!'
  else
    action_date = Time.now
    File.open(f) do |listing|
      begin
        Date.parse(File.basename(f,".*")[0,10])
        log_path ="/var/log/pixways/update_images/#{File.basename(f,".*")[0,10].gsub('-','')}/"
      rescue ArgumentError
        log_path ="/var/log/pixways/update_images/#{File.ctime(f).strftime("%Y%m%d")}/"
      end
      Dir.mkdir(log_path) unless File.exists?(log_path)
      error_log = File.open("#{log_path}#{File.basename(f,".*")}.error-log","a+")
      listing.each_line do |l|
        ic = ic + 1
        l.strip!
        i = Image.where("#{options[:field]} = #{l.dump} #{search_str_complement}").first
        # i = Image.where("ms_image_id = #{l.dump}").first
        begin
          if i.nil?
            error_log.write("#{l} not found\n")
          else
            unless options[:provider]
              top_prov = RefreshProvider.find_by(provider_id: i.provider.id)
              top_prov_nb_updated = UpdatedListProvider.joins(:refresh_provider).where(refresh_providers:{provider_id: i.provider.id},created_at: Time.now().beginning_of_month..Time.now().end_of_month).sum(:nb_photos)
              top_quota = top_prov.blank? ? 0 : top_prov.total_update - top_prov_nb_updated
            end
            if top_quota > 0
              Image.update(i.id, reception_date: action_date)
              top_prov.update(nb_updated: top_prov_nb_updated+1)
              top_quota -= 1 if options[:provider]
              puts ic.to_s+' '+i.file_name+' updated'
              tc += 1
            else
              error_log.write("#{l} not updated, over TOP quota\n")
            end
          end unless l.blank?
        rescue Exception => error
          error_log.write("#{Time.now.strftime("%Y-%m-%d %H:%M:%S")} - [ERROR] : #{error}\n")
        end
      end
      UpdatedListProvider.create(refresh_provider_id: top_prov.id, nb_photos: tc, action_date: Time.now.strftime("%Y-%m-%d %H:%M:%S"), visionneuse: File.basename(f)) if options[:provider]
      error_log.close
      File.delete("#{log_path}#{File.basename(f,".*")}.error-log") if File.zero?("#{log_path}#{File.basename(f,".*")}.error-log")
    end
  end
end