#!/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", "name of the images table field used to search them. By default it is ms_image_id.") do |l|
    options[:field] = l
  end

  opts.on("-u field_to_update", "--field_to_update", "name of the images table field to be updated. By default it is reception_date.") do |l|
    options[:field_to_update] = l
  end

  opts.on("-v value_to_update", "--value_to_update", "value to put into field to be updated, if -u option is choosen, and value isn't into listing provided.") do |l|
    options[:value_to_update] = l
  end

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

  opts.on("--force", "Force value update (to skip flow field value controls)") do |l|
    options[:force] = true
  end

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

end.parse!

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

options[:field] = 'ms_image_id' if options[:field].blank?
options[:field_to_update]='reception_date' if options[:field_to_update].blank?
options[:force]=false if options[:force].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}"
    if options[:field_to_update]=='reception_date'
      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.end_of_day).sum(:nb_photos)
      top_quota = top_prov.blank? ? 0 : top_prov.total_update - top_prov_nb_updated
    end
  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
        begin
          if i.nil?
            error_log.write("#{l} not found\n")
          else
=begin
            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.end_of_day).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: Time.now)
              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
            # if field to update is flow, check if picture is already on PixPalace or PixPalace 2 (flow value is 4,5,7 or 8) to not loose information by overwritting it, except if Force option is true
            # ToDo : to remove when Paris Match PixTech flows process is fully automatic and flow value is checked inside this automatic process
            if options[:field_to_update]=='flow' && i.flow != 0 && options[:force]===false
              case options[:value_to_update].to_i
              when 3 # set to PixTech Private only
                if i.flow==4 || i.flow==5 # is already on PixTech Private, and PixPalace or PixPalace 2
                  options[:value_to_update] = i.flow # keep the flow value
                elsif i.flow==7  # is on PixTech Public and PixPalace
                  options[:value_to_update] = 4 # update to PixTech Private and PixPalace
                elsif i.flow==8  # is on PixTech Public and PixPalace 2
                  options[:value_to_update] = 5 # update to PixTech Private and PixPalace 2
                end
              when 6 # set to PixTech Public only
                if i.flow==7 || i.flow==8 # is already on PixTech Public, and PixPalace or PixPalace 2
                  options[:value_to_update] = i.flow # We keep the flow value
                elsif i.flow==4  # is on PixTech Private and PixPalace
                  options[:value_to_update] = 7 # update to PixTech Public and PixPalace
                elsif i.flow==5  # is on PixTech Private and PixPalace 2
                  options[:value_to_update] = 8 # update to PixTech Public and PixPalace 2
                end
              end
            end
            Image.update(i.id, "#{options[:field_to_update]}"=> options[:value_to_update])
            puts "#{ic.to_s} #{i.file_name} updated, '#{options[:field_to_update]}' set to #{options[:value_to_update]}"
            tc += 1
          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, Time.now: 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