#!/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 = {}

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') do |l|
    begin
      l.to_datetime
    rescue
      puts "Error : #{l} is not a valid date'}"
      exit
    end
    options[:from] = l
  end

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

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

  opts.on('-l stat_label', '--label', String, 'label of statistics to retrieve : BD, HD, Demande or video. Format if choose severals : [BH,HD]') do |l|
    options[:label] = l
  end

  opts.on('-u user_login', '--user', String, 'Login of a specific user') do |l|
    options[:login] = l
  end

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

end.parse!

unless options[:label].blank?
  label_id = OperationLabel.where(label: options[:label]).first.id
  if label_id.nil?
    puts 'Error : label or list of labels invalid.'
    exit
  end
end

user_login_query = ""
unless options[:login].blank?
  user_login= User.find_by(login: options[:login])
  if user_login.nil?
    puts "Error : User with login '#{options[:login]}' does not exist."
    exit
  else
    user_login_query = " and user_id=#{user_login.id}"
  end
end

if options[:from].blank?
  if options[:to].blank?
    if options[:label].blank?
      stats = Statistic.all
    else
      stats = Statistic.where('operation_label_id in (?)', label_id)
    end
  else
    if options[:label].blank?
      stats = Statistic.where('created_at <= ?', options[:to])
    else
      stats = Statistic.where('created_at <= ? and operation_label_id in (?)', options[:to], label_id)
    end
  end
else
  if options[:to].blank?
    if options[:label].blank?
      stats = Statistic.where('created_at >= ?', options[:from])
    else
      stats = Statistic.where('created_at >= ? and operation_label_id in (?)', options[:from], label_id)
    end
  else
    if options[:label].blank?
      stats = Statistic.where('created_at >= ? and created_at <= ?', options[:from], options[:to])
    else
      stats = Statistic.where('created_at >= ? and created_at <= ? and operation_label_id in (?)', options[:from], options[:to], label_id)
    end
  end
end

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