#!/usr/bin/env ruby
# PixTech author replication (provider only for now)
require 'fileutils'

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

def email_err(e, msg)
  puts " erreur = #{e} msg = #{msg}"
  ::UserMailer.send_msg("Erreur get_pixtech_authors_json.rb : #{e.inspect} – #{msg}").deliver_now
  FileUtils.mv(file, "#{file}-err")
end

def create_author(author,prov,pixtech)
  if pixtech.nil?
    puts "[#{Time.now().strftime("%Y-%m-%d %H:%M:%S")}] Error : pixtech #{author['pixtech_name']} does not exist"
    return false
  else
    if prov.nil?
      begin
        prov = Provider.create_provider(author['name'], author['pp_name'], author['string_key'], author['copyright_rule'],author['pp_string_key'],author['description'],pixtech.id,author['provider_type_id'],author['local'], '','','','')
      rescue => e
        puts "[#{Time.now().strftime("%Y-%m-%d %H:%M:%S")}] Error #{e.inspect} – provider #{author['string_key']}"
        return false
      else
        return true
      end
    else
      puts "[#{Time.now().strftime("%Y-%m-%d %H:%M:%S")}] Error : provider #{author['string_key']} already exists"
      return true
    end
  end

  #ToDo : replicate everything for full test environment?
=begin
  tpgname = photog ? "ph_#{sk}" : sk
  tpgn = ::TitleProviderGroupName.find_by_name(tpgname)
  if tpgn.nil?
    begin
      tpgn = ::TitleProviderGroupName.create_tpgn(tpgname)
    rescue => e
      email_err(e, " erreur creation TitleProviderGroupName #{sk} PTref1")
      prov.destroy
      exit
    end
    tpg = ::TitleProviderGroup.create(title_provider_group_name_id: tpgn.id, provider_id: prov.id)
    ::Authorization.create(permission_label_id: 1, title_provider_group_id: tpg.id)
    ::Authorization.create(permission_label_id: 2, title_provider_group_id: tpg.id)
    idsg = ::TitleProviderGroupName.find_by_name('toutes').id
    tpg = ::TitleProviderGroup.create(title_provider_group_name_id: idsg, provider_id: prov.id)
    ::Authorization.create(permission_label_id: 1, title_provider_group_id: tpg.id)
    ::Authorization.create(permission_label_id: 2, title_provider_group_id: tpg.id)
    if photog
      idsg = ::TitleProviderGroupName.find_by_name('photographes').id
    else
      idsg = ::TitleProviderGroupName.find_by_name('agences').id
    end
    tpg = ::TitleProviderGroup.create(title_provider_group_name_id: idsg, provider_id: prov.id)
    ::Authorization.create(permission_label_id: 1, title_provider_group_id: tpg.id)
    ::Authorization.create(permission_label_id: 2, title_provider_group_id: tpg.id)
  end
  t = ::Title.find_by_name(tpgname)
  if t.nil?
    begin
      t = ::Title.create_title(tpgname, tpgn.id)
    rescue => e
      email_err(e, " erreur creation Title #{sk} PTRef1")
      prov.destroy
      tpgn.destroy
      exit
    end
  end
  u = ::User.find_by_email(email)
  unless u.nil?
    u.destroy
  end
  begin
    u = ::User.create(login: login, first_name: first_name, last_name: last_name, email: email,
                      title_id: t.id, password: mdp, password_confirmation: mdp, roles_mask: 8)
  rescue => e
    email_err(e, " erreur creation user #{login} PTRef1")
    prov.destroy
    tpgn.destroy
  end
  u.update_attributes(authentication_token: token)
=end

end

def destroy_author(author,prov,pixtech)
  if prov.nil?
    puts "[#{Time.now().strftime("%Y-%m-%d %H:%M:%S")}] Error : provider #{author['string_key']} not found"
    return true
  else
    begin
      prov.destroy
    rescue => e
      puts "[#{Time.now().strftime("%Y-%m-%d %H:%M:%S")}] Error #{e.inspect} – provider #{author['string_key']}"
      return false
    else
      return true
    end
  end

  #ToDo : destroy everything when procedure to create would have been done (see above in create loop)
=begin
  tpgname = photog ? "ph_#{sk}" : sk
  tpgn = ::TitleProviderGroupName.find_by_name(tpgname)
  if tpgn.nil?
    begin
      tpgn = ::TitleProviderGroupName.create_tpgn(tpgname)
    rescue => e
      email_err(e, " erreur creation TitleProviderGroupName #{sk} PTref1")
      prov.destroy
      exit
    end
    tpg = ::TitleProviderGroup.create(title_provider_group_name_id: tpgn.id, provider_id: prov.id)
    ::Authorization.create(permission_label_id: 1, title_provider_group_id: tpg.id)
    ::Authorization.create(permission_label_id: 2, title_provider_group_id: tpg.id)
    idsg = ::TitleProviderGroupName.find_by_name('toutes').id
    tpg = ::TitleProviderGroup.create(title_provider_group_name_id: idsg, provider_id: prov.id)
    ::Authorization.create(permission_label_id: 1, title_provider_group_id: tpg.id)
    ::Authorization.create(permission_label_id: 2, title_provider_group_id: tpg.id)
    if photog
      idsg = ::TitleProviderGroupName.find_by_name('photographes').id
    else
      idsg = ::TitleProviderGroupName.find_by_name('agences').id
    end
    tpg = ::TitleProviderGroup.create(title_provider_group_name_id: idsg, provider_id: prov.id)
    ::Authorization.create(permission_label_id: 1, title_provider_group_id: tpg.id)
    ::Authorization.create(permission_label_id: 2, title_provider_group_id: tpg.id)
  end
  t = ::Title.find_by_name(tpgname)
  if t.nil?
    begin
      t = ::Title.create_title(tpgname, tpgn.id)
    rescue => e
      email_err(e, " erreur creation Title #{sk} PTRef1")
      prov.destroy
      tpgn.destroy
      exit
    end
  end
  u = ::User.find_by_email(email)
  unless u.nil?
    u.destroy
  end
  begin
    u = ::User.create(login: login, first_name: first_name, last_name: last_name, email: email,
                      title_id: t.id, password: mdp, password_confirmation: mdp, roles_mask: 8)
  rescue => e
    email_err(e, " erreur creation user #{login} PTRef1")
    prov.destroy
    tpgn.destroy
  end
  u.update_attributes(authentication_token: token)
=end
end

# create author and all associations (provider, user, title, group, authorization,..)
FileUtils::makedirs("../public/pixtech_authors/error/") unless Dir.exists?("../public/pixtech_authors/error/")
FileUtils::makedirs("../public/pixtech_authors/archive/") unless Dir.exists?("../public/pixtech_authors/archive/")
files = Dir['../public/pixtech_authors/pixtech_author_*.json'].sort_by(&File.method(:mtime))
files.each do |file|
  author = JSON.parse open(file).read
  puts" author #{author.inspect}"
  prov = Provider.find_by(string_key: author['string_key'])
  pixtech = Pixtech.find_by(name: author['pixtech_name'])
  res = create_author(author,prov,pixtech) if file.include?('pixtech_author_create_')
  res = destroy_author(author,prov,pixtech) if file.include?('pixtech_author_destroy_')
  case res
  when true
    puts "File #{file} processed, moved to public/pixtech_authors/archive/ folder"
    FileUtils.mv(file, "../public/pixtech_authors/archive/")
  when false
    puts "File #{file} not processed, moved to public/pixtech_authors/error/ folder"
    FileUtils.mv(file, "../public/pixtech_authors/error/")
  end
end