#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/../config/environment.rb'
require 'optparse'
require 'pixways'

def api_call(demand, login, var_id, parameters={})
  unless Server.itself? PIXADMIN_SERVER_NAME
    server_url = "http://#{Server.find_by_name('Pixadmin').host}:#{Server.find_by_name('Pixadmin').api_port}/"
    cs_name = Server.find_by_is_self(true).name
    api_res = ''
    url_key = 'cs_request'
    safeurl = URI.encode("#{server_url}#{url_key}".strip)
    message = {'cs_demand' => demand, 'cs_name' => cs_name, 'user_login' => login, 'var_id' => var_id, 'parameters' => parameters }
    begin
      res = RestClient.post( safeurl, message.to_json, content_type: :json, accept: :json)
    rescue => e
      puts "rescue #{e.inspect}"
      api_res = "Erreur Rest : #{e.inspect}"
    end
    if api_res.blank?
      if Pixways.valid_json(res.body)
        retour = JSON.parse(res.body)
        api_res = retour['result']
      end
    else
      newjob = CommunicationOutJob.new
      newjob.params = message
      newjob.result = api_res
      newjob.done = 100
      newjob.save
    end
    puts "result api = #{api_res}"
  end
end

options = {}
options[:from] = ""
options[:to] = ""
options[:label] = OperationLabel.all.pluck(:id)
options[:user] = ""

OptionParser.new do |opts|
  opts.banner = 'Usage: send_stats_to_pixadmin [options]'

  opts.on('-f date_from', '--from', String, 'Date to retrieve the statistics from (format dd/mm/aaaa)') do |l|
    begin
      l.to_datetime
    rescue
      puts "Error : #{l} is not a valid date, format must be 'dd/mm/aaaa'"
      exit
    end
    options[:from] = l
  end

  opts.on('-t date_to', '--to', String, 'Date to retrieve the statistics until (format dd/mm/aaaa)') do |l|
    begin
      l.to_datetime
    rescue
      puts "Error : #{l} is not a valid date, format must be 'dd/mm/aaaa'"
      exit
    end
    options[:to] = l
  end

  opts.on('-l stat_label', '--label', String, 'label of statistics to retrieve : BD, HD, Demande or video.') do |l|
    options[:label] = OperationLabel.where(label: l).pluck(:id)
    if options[:label].blank?
      puts 'Error : label or list of labels invalid.'
      exit
    end
  end

  opts.on('-u user_login', '--user', String, 'Login of a specific user') do |l|
    options[:user] = User.find_by(login: l).id
    if options[:user].blank?
      puts "Error : User with login '#{l}' does not exist."
      exit
    end
  end

  options[:dryrun]=false
  opts.on('-d','--dryrun','dry run, show what will be done') do
    options[:dryrun]=true
  end

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

end.parse!

stats = Statistic.where(created_at: Pixways.dates_to_range(options[:from], options[:to], false), operation_label_id: options[:label], user_id: options[:user])
puts "number of stats to send : #{stats.count}"
stats.each do |stat|
  user_login = User.find(stat.user_id).login
  img = Image.find(stat.image_id)
  parameters = { type_op: stat.operation_label_id, date_op: stat.created_at.to_s}
  if options[:dryrun]
    puts "api_call('stat', #{user_login}, #{img.ms_image_id}), #{parameters}" unless Provider.find(img.provider_id).local?
  else
    api_call('stat', user_login, img.ms_image_id, parameters) unless Provider.find(img.provider_id).local?
  end
end