#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/../config/environment.rb'
require 'optparse'
require 'optparse/time'

# Check if physical thumb and medium files exist according to thumb_location and medium_location pathes in images table

options = {}
options[:content_error] = false

OptionParser.new do |opts|
  # opts.banner = "Usage: check_image_files.rb [parameters]. At least a string_key or a list of images."
  opts.banner = "Usage: check_image_files.rb [parameters]. At least a string_key or a pp_string_key."

=begin
  opts.on("-l list.txt", "File name of the images list. Optional.") do |l|
    options[:list] = l
  end

  opts.on("-f field", "Field used to search in images table, when a list is given. By default file_name.") do |l|
    options[:field] = l
  end
=end

  opts.on("-p string_key", "String_key of provider to check all images of. Optional") do |l|
    options[:string_key] = l
  end

  opts.on("-t pp_string_key", "pp_string_key of providers to check all images of. Optional") do |l|
    options[:pp_string_key] = l
  end

  opts.on("-ce","--content_error" "Search images with content_error to true (is false by default). Optional") do |l|
    options[:content_error] = true
  end

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end

end.parse!

if options[:string_key].blank? && options[:list].blank? && options[:pp_string_key].blank?
  # puts 'Error : not enough parameter. At least 1 is required (a string_key or a list). Use -h or --help for help'
  puts 'Error : not enough parameter. At least 1 is required (a string_key or a pp_string_key). Use -h or --help for help'
  exit
end

unless options[:string_key].blank?
  prov_id = Provider.where(string_key: options[:string_key]).pluck(:id)
  if prov_id.nil?
    puts "Error : no provider found with string_key '#{options[:string_key]}'"
    exit
  end
end

unless options[:pp_string_key].blank?
  prov_id = Provider.where(pp_string_key: options[:pp_string_key], provider_type_id: 2).pluck(:id)
  if prov_id.nil?
    puts "Error : no provider found with pp_string_key '#{options[:pp_string_key]}'"
    exit
  end
end

i=0
missing_thumb = 0
missing_medium = 0
if options[:string_key].blank? && options[:pp_string_key].blank?
  log_filename = "check_image_files_#{Time.now.strftime("%Y%m%d-%H%M%S")}.log"
elsif !options[:pp_string_key].blank?
  log_filename = "check_image_files_#{options[:pp_string_key]}.log"
else
  log_filename = "check_image_files_#{options[:string_key]}.log"
end
log_file = File.open(log_filename, "a", sync: true)
log_file.puts("Begin - #{Time.now}")

imgs = Image.where(provider_id: prov_id, content_error: options[:content_error]).select(:ms_image_id, :original_filename, :file_name, :thumb_location, :medium_location, :hires_location)
if imgs.blank?
  if !options[:pp_string_key].blank?
    log_file.puts("Warning : no image found for providers with pp_string_key '#{options[:pp_string_key]}'.")
  else
    log_file.puts("Warning : no image found for provider with string_key '#{options[:string_key]}'.")
  end
else
  if !options[:pp_string_key].blank?
    log_file.puts("Info : #{imgs.size} images found for providers with pp_string_key '#{options[:pp_string_key]}'.")
  else
    log_file.puts("Info : #{imgs.size} images found for provider with string_key '#{options[:string_key]}'.")
  end

  log_file.puts("File(s) not found (csv format) :")
  log_file.puts("ms_image_id;original_filename;file_name;missing file for thumb_location;missing file for medium_location;hires_location")
  imgs.each do |img|
      i+=1
      missed_thumb_location = false
      missed_med_location = false  
      
      # Check thumb file
      if !File.file?("#{Rails.root}/public#{img.thumb_location}")        
        missing_thumb += 1
        missed_thumb_location = true
      end
      if !File.file?("#{Rails.root}/public#{img.medium_location}")        
        missing_medium += 1
        missed_med_location = true
      end      
      
      if missed_thumb_location || missed_med_location
        log_file.write("#{img.ms_image_id};#{img.original_filename};#{img.file_name}")
        if missed_thumb_location
          log_file.write(";#{img.thumb_location}")
        else
          log_file.write(";")
        end
        if missed_med_location
          log_file.write(";#{img.medium_location}")
        else
          log_file.write(";")
        end        
        log_file.write(";#{img.hires_location}\n")
      end      
    end
end

log_file.puts("End - #{Time.now}")
log_file.puts "#{i} images checked. #{missing_thumb} missing thumb files, #{missing_medium} missing medium files."
log_file.close
puts "#{i} images checked. #{missing_thumb} missing thumb files, #{missing_medium} missing medium files. Log file : #{log_filename}"
