#!/usr/bin/env ruby
require 'optparse'
require File.dirname(__FILE__) + '/../config/environment.rb'

#Retrieve updated_at values from old Abaca button (Abaca) to new ones (Abacanewsroy and Abacacelebsport)

options = {}
options[:dry_run] = false

OptionParser.new do |opts|
  opts.banner = "Usage: recup_updatedat [options]"

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

  opts.on("-N", "--no-action", "images wont be updated, just listed") do
    options[:dry_run] = true
  end

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

end.parse!

if options[:provider]
  log_filename = "recup_updatedat_#{options[:provider]}_#{Time.now.strftime('%Y-%m-%d-%Hh%Mm%S')}.log"
else
  log_filename = "recup_updatedat_#{Time.now.strftime('%Y-%m-%d-%Hh%Mm%S')}.log"
end
file_log = File.open(log_filename,"a+")
file_log.write("BEGIN at #{Time.now.strftime('%Hh%Mm%S')}\n")

file_log.write("Start getting pictures list - #{Time.now.strftime('%Hh%Mm%S')}\n")
if options[:provider]
  prov = Provider.find_by(string_key: options[:provider])
  if prov.blank?
    file_log.write("Error : string_key not found.\n")
    puts "Error : string_key not found."
    exit
  else
    imgs_to_update = Image.where(provider_id: prov.id, content_error: 0)
  end
else
  provs_id = Provider.where(string_key: ['Abacanewsroy','Abacacelebsport']).pluck(:id)
  imgs_to_update = Image.where(provider_id: provs_id, content_error: 0)
end

if imgs_to_update.blank?
  file_log.write("Error : no images found.\n")
  puts "Error : no images found."
  exit
else
  file_log.write("Start processing pictures (#{imgs_to_update.count}) - #{Time.now.strftime('%Hh%Mm%S')}\n")
  prov_abacapress = Provider.find_by(string_key: 'Abaca')
  imgs_to_update.each do |img_to_update|
    if img_to_update.created_at == img_to_update.updated_at
    img_abacapress = Image.where(provider_id: prov_abacapress.id, original_filename: img_to_update.original_filename, content_error: 0)
    if img_abacapress.blank?
      # Search if image is on PP2
      begin
        config_db_pp2 = Rails.configuration.database_configuration["pixpalace2"]
        pp2_client = Mysql2::Client.new(:host => config_db_pp2["host"],:database => config_db_pp2["database"],:username => config_db_pp2["username"], :password => config_db_pp2["password"])
        pp2_img_abacapress=pp2_client.query("select * from images where original_filename='#{pp2_client.escape(img_to_update.original_filename)}' and provider_id=(select id from providers where string_key='Abaca') and content_error=0")
      rescue Mysql2::Error => e
        file_log.write("Error #{e.message} on #{config_db_pp2["host"]}\n")
        pp2_client.close
        next
      end
      if pp2_img_abacapress.first.blank?
        file_log.write("Warning : #{img_to_update.file_name} : Abaca Press image not found.\n")
      elsif pp2_img_abacapress.count > 1
        file_log.write("Warning : #{img_to_update.file_name} : more than one Abaca Press image with original_filename = '#{img_to_update.original_filename}' found on PP2, skipping image.\n")
      else
        pp2_i_abacapress = pp2_img_abacapress.first
        if img_to_update.updated_at <= pp2_i_abacapress['updated_at']
          file_log.write("Warning : #{img_to_update.file_name} : Abaca Press image found on PP2 but updated_at value is more recent, skipping image.\n")
        else
          if options[:dry_run]
            file_log.write("Info : #{img_to_update.file_name} : Abaca Press image found on PP2, updated_at would be updated from #{img_to_update.updated_at} to #{pp2_i_abacapress['updated_at']}, and created_at from #{img_to_update.created_at} to #{pp2_i_abacapress['created_at']}.\n")
          else
            file_log.write("Info : #{img_to_update.file_name} : Abaca Press image found on PP2, updated_at is updated from #{img_to_update.updated_at} to #{pp2_i_abacapress['updated_at']}, and created_at from #{img_to_update.created_at} to #{pp2_i_abacapress['created_at']}.\n")
            img_to_update.update(updated_at: pp2_i_abacapress['updated_at'],created_at: pp2_i_abacapress['created_at'])
          end
        end
      end
      pp2_client.close
    elsif img_abacapress.count > 1
      file_log.write("Warning : #{img_to_update.file_name} : more than one Abaca Press image with original_filename = '#{img_to_update.original_filename}' found, skipping image.\n")
    else
      i_abacapress = img_abacapress.first
      if img_to_update.updated_at <= i_abacapress.updated_at
        file_log.write("Warning : #{img_to_update.file_name} : Abaca Press image found but updated_at value is more recent, skipping image.\n")
      else
        if options[:dry_run]
          file_log.write("Info : #{img_to_update.file_name} : Abaca Press image found, updated_at would be updated from #{img_to_update.updated_at} to #{i_abacapress.updated_at}, and created_at from #{img_to_update.created_at} to #{i_abacapress.created_at}.\n")
        else
          file_log.write("Info : #{img_to_update.file_name} : Abaca Press image found, updated_at is updated from #{img_to_update.updated_at} to #{i_abacapress.updated_at}, and created_at from #{img_to_update.created_at} to #{i_abacapress.created_at}.\n")
          img_to_update.update(updated_at: i_abacapress.updated_at,created_at: i_abacapress.created_at)
        end
      end
    end
    else
      file_log.write("Warning : #{img_to_update.file_name} : updated_at has already been updated, skipping image.\n")
    end
  end
  file_log.write("END at #{Time.now.strftime('%Hh%Mm%S')}\n")
  file_log.close
end