#!/usr/bin/env ruby

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

#Light Motiv stats
=begin
#stats = CSV.read('missedStats.csv')
prov = ''
prov_stats = File.open("cut_csv_horizontaly_tmp.csv", 'w')

CSV.foreach('2018-11-15_Lightmotiv_photographers_pictures_all.csv', headers: true) do |row|
  if prov != row[1]
    prov_stats.close if defined?prov_stats
    prov_stats = File.open("Light Motiv - #{row[1]}.csv", 'w')
    #CSV.open("missedStats_#{row[3]}.csv", 'w') do |prov_stats|
    prov_stats.write(row.headers.to_csv)
    prov = row[1]
  end
  prov_stats.write("#{row}")
end

prov_stats.close
=end

# Kharbine PixTech (update metadata and if needed sending to PP or PP2)
options = {}
options[:sep] = ','

OptionParser.new do |opts|
  opts.banner = "Usage: cut_csv_horizontally file.csv [options]"

  opts.on("-d", "--destination [PP_or_PP2]",String, "destination") do |l|
    if l=='PP' || l=='PP2'
      options[:dest] = l
    else
      puts "Error : destination must be 'PP' or 'PP2', use -h or --help for help"
      exit
    end
  end

  opts.on("-f", "--folder [name]",String, "folder where to write the resulting CSV files") do |l|
    options[:folder] = l
  end

  opts.on("-s", "--separator", String, "fields separator (default is ',') ") do |l|
    options[:sep] = l
  end

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

end.parse!

if ARGV.blank?
  puts 'Error : CSV file name needed, use -h or --help for help'
  exit
end

ARGV.collect do |f|
  i = 0

  CSV.foreach(f, headers: true, return_headers: false, col_sep: options[:sep]) do |csv_line|
    line_to_write=[]
    img_filename = "#{csv_line[0]}.#{csv_line[1]}"
    csv_filename = "#{File.basename(img_filename,".*")}.csv"

    img = Image.find_by(file_name: img_filename)

    if img.nil?
      puts "Warning : image with file_name '#{img_filename}' not found"
    else
      begin
        unless options[:folder].blank?
          Dir.mkdir(options[:folder]) unless File.exists?(options[:folder])
          csv_filename = "#{options[:folder]}/#{csv_filename}"
        end
        CSV.open(csv_filename, 'w',  {col_sep: ',', quote_char: '"', force_quotes: true}) do |csv|
          if options[:dest].blank?
            # csv << csv_line.headers[2..-1].push('3:230','3:213')
            csv << ['2:105','2:120','2:90','2:101','2:95','2:110','2:40','2:20','2:025','2:5','2:15','2:55','2:103','2:10','2:12','2:85','2:92','2:121','2:122','3:230','3:213']
          else
            # csv << csv_line.headers[2..-1].push('3:230','3:213','3:238')
            csv << ['2:105','2:120','2:90','2:101','2:95','2:110','2:40','2:20','2:025','2:5','2:15','2:55','2:103','2:10','2:12','2:85','2:92','2:121','2:122','3:230','3:213','3:238']
          end
          for c in (2..10)
            line_to_write.push("#{csv_line[c]}")
          end
          #Empty other fields ('2:5','2:15','2:55','2:103','2:10','2:12','2:85','2:92','2:121','2:122')
          for c in (1..10)
            line_to_write.push("")
          end
          line_to_write.push("#{img.ms_picture_id}","#{img.hires_location}")
          line_to_write.push("#{options[:dest]}") unless options[:dest].blank?
          csv << line_to_write
        end

        case options[:dest]
        when 'PP'
          img.update(flow: 1)
        when 'PP2'
          img.update(flow: 2)
        end
        i+=1

      rescue Exception => e
        puts "ERROR : #{e}"
      end
    end
    break
  end
  puts "Finished : #{i} CSV files created"
end
