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

options = {}
options[:dry_run] = false

OptionParser.new do |opts|
  opts.banner = "Usage: pixtech_flow_update [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("-t 'pixtech name'", "--pixtech_name 'pixtech name'", String, "Images will be updated for this pixtech only") do |o|
    options[:pixtech] = o
  end

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

  # opts.on("-r ", "--reset", String, "Flow field will be reset to 0 before update") do |o|
  #   options[:reset] = o
  # end

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

end.parse!

if options[:pixtech]
  log_filename = "pixtech_flow_update_#{options[:pixtech]}_#{Time.now.strftime('%Y-%m-%d-%Hh%Mm%S')}.log"
elsif options[:provider]
  log_filename = "pixtech_flow_update_#{options[:provider]}_#{Time.now.strftime('%Y-%m-%d-%Hh%Mm%S')}.log"
else
  log_filename = "pixtech_flow_update_#{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[:pixtech]
  pixtech = Pixtech.find_by(name: options[:pixtech])
  if pixtech.blank?
    file_log.write("Error : pixtech name not found.\n")
    puts "Error : pixtech name not found."
    exit
  else
    imgs_author = Image.joins(:provider).where(providers: {pixtech_id: pixtech.id, provider_type_id: 2}, content_error: 0)
  end
elsif 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
  elsif prov.provider_type_id == 2
    imgs_author = Image.where(provider_id: prov.id, content_error: 0)
  else
    provs_id = Provider.where(pp_string_key: options[:provider], provider_type_id: 2).pluck(:id)
    imgs_author = Image.where(provider_id: provs_id, content_error: 0)
  end
else
  provs_id = Provider.where(provider_type_id: 2).pluck(:id)
  imgs_author = Image.where(provider_id: provs_id, content_error: 0)
end

if imgs_author.blank?
  file_log.write("Error : no images found.\n")
  puts "Error : no images found."
  exit
else
  file_log.write("Start processing pictures (#{imgs_author.count}) - #{Time.now.strftime('%Hh%Mm%S')}\n")
  imgs_author.each do |img_author|
    prov_stock = Provider.find_by(string_key: img_author.provider.pp_string_key, provider_type_id: 1)
    img_stock = Image.where(provider_id: prov_stock.id, original_filename: img_author.original_filename, content_error: 0)
    if img_stock.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_stock=pp2_client.query("select * from images where original_filename='#{pp2_client.escape(img_author.original_filename)}' and provider_id=(select id from providers where string_key='#{img_author.provider.pp_string_key}') 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_stock.first.blank?
        unless img_author.flow == 0
          if options[:dry_run]
            file_log.write("Warning : #{img_author.file_name} : stock image not found, flow value would be set to 0.\n")
          else
            img_author.update(flow: 0)
            file_log.write("Warning : #{img_author.file_name} : stock image not found, flow value is set to 0.\n")
          end
        end
      else
        unless img_author.flow == 2
          if options[:dry_run]
            file_log.write("Info : #{img_author.file_name} : stock image found on PP2, flow value would be set to 2.\n")
          else
            img_author.update(flow: 2)
            file_log.write("Info : #{img_author.file_name} : stock image found on PP2, flow value is set to 2.\n")
          end
        end
      end
      pp2_client.close
    elsif img_stock.count > 1
      file_log.write("Warning : #{img_author.file_name} : more than one #{img_author.provider.pp_string_key} image with original_filename = '#{img_author.original_filename}'. Skipping image.\n")
    else
      i_stock = img_stock.first
      unless img_author.flow == 1
        if options[:dry_run]
          file_log.write("Info : #{img_author.file_name} : stock image found, flow value would be set to 1.\n")
        else
          img_author.update(flow: 1)
          file_log.write("Info : #{img_author.file_name} : stock image found, flow value is set to 1.\n")
        end
      end
      unless i_stock.flow == 0
        if options[:dry_run]
          file_log.write("Info : #{i_stock.file_name} : stock image flow value = #{i_stock.flow}, flow value would be set to 0.\n")
        else
          i_stock.update(flow: 0)
          file_log.write("Info : #{i_stock.file_name} : stock image flow value = #{i_stock.flow}, flow value is set to 0.\n")
        end
      end
    end
  end
  file_log.write("END at #{Time.now.strftime('%Hh%Mm%S')}\n")
  file_log.close
  #File.delete(log_filename) if File.zero?(log_filename)
end