RMAGICK_BYPASS_VERSION_TEST = true
require 'csv'
require 'rmagick'
require 'fileutils'
require 'net/ftp'
require 'mysql2'
require 'json'
require 'rest_client'
require 'pixways'

class Provider < ActiveRecord::Base

  include Pixways

  has_many :title_provider_groups, dependent: :destroy
  has_many :title_provider_group_names, through: :title_provider_groups
  has_many :search_provider_groups, dependent: :destroy
  has_many :search_provider_group_names, through: :search_provider_groups
  has_many :selected_providers_for_requests, dependent: :destroy
  has_many :request_to_providers, through: :selected_providers_for_requests
  has_many :images
  has_many :provider_contacts, dependent: :destroy
  accepts_nested_attributes_for :provider_contacts, reject_if: proc { |attributes| attributes[:email].blank? }, allow_destroy: true
  belongs_to :pixtech

  mount_uploader :logo, LogoUploader
  mount_uploader :pdf, PdfUploader
  mount_uploader :formu, FormuUploader

  validates :string_key, presence: true, uniqueness: { case_sensitive: false }
  validates :name, presence: true, uniqueness: { case_sensitive: false } unless :is_author?
  validates :copyright_rule, :country, presence: true

  before_save do |prov|
    prov.pp_string_key = prov.string_key if prov.pp_string_key.blank?
  end

  after_create do |prov|
    RefreshProvider.create(provider_id: prov.id, nb_updated: 0, total_update: 200)
  end

  before_destroy do |prov|
    author_destroy(prov) if (prov.is_pixtech_author? && Server.itself?(PIXADMIN_SERVER_NAME))
    Statistic.joins(:image).where(images: { provider_id: prov.id }).collect{ |s| s.destroy }
    #Reportage.where(string_key: prov.string_key).collect{|r| r.destroy} # Useless because of reportage_photos association and destroy / update functions - Allow to not destroy photo subject containing pictures of several providers (PixTech Kharbine)
    Image.where(provider_id: prov.id).collect{|i| i.delete_hr}
    FileUtils.rm_rf("public/images/photos/#{prov.string_key}")
  end

  def self.get_from_file_name(file_name)
    #f = File.basename(file_name)#.upcase
    pname = File.basename(file_name).split('.').first
    pname = 'Sipa' if pname == 'SIPAUSA'
    #prov = nil
    #all.each{|p| prov = p if p.string_key.upcase == pname }
    self.find_by(string_key: pname)
    #prov
  end

  def self.get_from_input_dir(input_dir)
    ( @@_by_input_dir ||= {} )[input_dir] ||= find_by_input_dir(input_dir)
  end

  def self.find_my_provs(provs)
    l_prov = []
    provs.each_index{|i| l_prov << i if provs[i] == 1}
    self.where(id: l_prov).order(:name)
  end

  def self.create_provider(name, pp_name, s_k, coprule, pp_string_key='', description='', pixtech_id=nil, provtype=1, local, pk, nb_pk, ir_web, ir_print)
    self.create(name: name, pp_name: pp_name, string_key: s_k, country: "France", copyright_rule: coprule, pp_string_key: pp_string_key, pixtech_id: pixtech_id, provider_type_id: provtype, local: local, description: description)
  end

  def self.stats_3months
    if Server.itself?(PIXADMIN_SERVER_NAME)
      users = User.where('roles_mask not in (1,8,16,32,128)').collect{|u| u.id}
      month_range = (Date.today-1.month).at_beginning_of_month..(Date.today-1.month).at_end_of_month
      months_range = (Date.today-3.month).at_beginning_of_month..(Date.today-1.month).at_end_of_month
      end_month = (Date.today-1.month).at_end_of_month.day
      prev_month = I18n.t('date.month_names')[(Date.today-1.month).month]
      prov_hd = {}
      prov_1mois = {}
      total_prov_hd = 0
      total_prov_1mois = 0

      self.where(local: false).order(:pp_name).each do |prov|
        statshd = Statistic.joins(:image).where(images: {provider_id: prov.id}, statistics: {user_id: users, created_at: months_range}).count
        prov_hd[prov.pp_name] = statshd
        total_prov_hd += statshd

        statsm = Statistic.joins(:image).where(user_id: users, images: {provider_id: prov.id}, statistics: {created_at: month_range}).count
        prov_1mois[prov.pp_name] = statsm
        total_prov_1mois += statsm
      end
      UserMailer.prov_3monthsstats(end_month, prev_month, prov_hd, total_prov_hd, prov_1mois, total_prov_1mois).deliver_now
    end
  end

  def self.send_yas
    #if Server.itself?([*PIXADMIN_SERVER_NAME,*PP2_SERVER_NAME,*PTREF_SERVER_NAME])
    if Server.itself?(PIXADMIN_SERVER_NAME) || Server.itself?(PP2_SERVER_NAME) || Server.itself?(PTREF_SERVER_NAME)
      server_name = Server.find_by_is_self(true).name
      total_photos = 0
      total_photos_source = {}
      total_photos_source_web = {}
      total_photos_source_print = {}
      source_list = []
      service_source = 3
      prov = {}
      prov_csv = {}
      today = Date.today.strftime('%Y-%m-%d')
      header = ['string_key','date_nb_photos','nb_photos','service']
      export = ''
      export.encode!('UTF-8')
      if server_name == PTREF_SERVER_NAME && Server.itself_production?
        file = "pt_facturation_#{today}.csv"
        prov_print = {}
        prov_service = {}
        ['Afacturer_print', 'Afacturer_web'].each do |af|
          self.where("#{af} = true").order(:name).each do |p|
            nb_photos = Image.search_count with:{provider_id: p.id, content_error: false}
            unless nb_photos == 0
              if p.from_source != 'Pixways'
                source_list << p.from_source unless source_list.include?(p.from_source)
                total_photos_source[p.from_source] = (total_photos_source[p.from_source] || 0) + nb_photos
                total_photos_source_web[p.from_source] = (total_photos_source_web[p.from_source] || 0) + nb_photos if p.index_IR_web === true
                total_photos_source_print[p.from_source] = (total_photos_source_print[p.from_source] || 0) + nb_photos if p.index_IR_print == 1
              else
                prov[p.name] = [nb_photos,p.string_key]
                if p.index_IR_web === true
                  prov_csv[p.string_key] = nb_photos
                  prov_service[p.string_key] = p.type_service_web
                end
                prov_print[p.string_key] = nb_photos if p.index_IR_print == 1
              end
              total_photos += nb_photos
            end
          end

          source_list.each do |source|
            prov[source] = [total_photos_source[source],source]
            if total_photos_source_web[source]
              prov_csv[source] = total_photos_source_web[source]
              prov_service[source] = service_source
            end
            prov_print[source] = total_photos_source_print[source] if total_photos_source_print[source]
          end

          UserMailer.send_yas(prov, total_photos, server_name, af).deliver_now
          total_photos = 0
          total_photos_source = {}
          total_photos_source_web = {}
          total_photos_source_print = {}
          source_list = []
          prov = {}
        end

        CSV(export, {col_sep: ';'}) do |csv|
          csv << header
          prov_csv.each do |k, v|
            csv << [k, today, v, prov_service[k]]
          end
          prov_print.each do |k, v|
            csv << [k, today, v, 1]
          end
        end
      else
        if server_name == PIXADMIN_SERVER_NAME
          file = "pp_facturation_#{today}.csv"
          service = 1
        else
          file = "pp2_facturation_#{today}.csv"
          service = 2
        end
        service_pixtech = 3
        total_photos_pixtech_authors = {}
        pixtech_list = []

        self.where(actif: true).order(:name).each do |p|
          nb_photos = Image.search_count with:{provider_id: p.id, content_error: false}
          unless nb_photos == 0
            if p.is_pixtech_author?
              pixtech_name = p.pixtech.pixtech_params.find_by(name:'full_name').value
              p.pixtech.pixtech_param.full_name rescue nil
              pixtech_list << pixtech_name unless pixtech_list.include?(pixtech_name)
              total_photos_pixtech_authors[pixtech_name] = (total_photos_pixtech_authors[pixtech_name] || 0) + nb_photos
            else
              prov[p.pp_name] = [nb_photos,p.string_key,service]
            end
            total_photos += nb_photos
          end
        end
        pixtech_list.each do |pixtech_name|
          prov["#{pixtech_name}_PixTech"] = [total_photos_pixtech_authors[pixtech_name],pixtech_name,service_pixtech]
        end

        prov = prov.sort_by {|k,v| k}

        CSV(export, {col_sep: ';'}) do |csv|
          csv << header
          prov.each do |k, v|
            csv << [v[1], today, v[0], v[2]]
          end
        end

        UserMailer.send_yas(prov, total_photos, server_name, "").deliver_now

      end

      File.open("/tmp/#{file}", 'wb'){ |f| f.write(export)}
      begin
        Net::SCP.upload!('subscribe.pixtrakk.com', 'pixtrakk', "/tmp/#{file}", "/var/www/subscribe.pixtrakk.com/current/public/dev/#{file}")
        #File.delete("tmp/#{file}")
      rescue => e
        puts " erreur SCP #{e}"
      end

    end
  end

  def self.check_controls(reference_date = Date.today - 1.day)
    if Server.itself?(PIXADMIN_SERVER_NAME)
      reference_date = reference_date.instance_of?(String)? Date.parse(reference_date) : Date.parse(reference_date.strftime)
      reference_time = Time.parse(reference_date.strftime)
      ddeb = reference_time.midnight
      dfin = reference_time.end_of_day
      config_db_ms = Rails.configuration.database_configuration['ms_db']
      client = Mysql2::Client.new(:host => config_db_ms['host'], :database => config_db_ms['database'], :username => config_db_ms['username'], :password => config_db_ms['password'])

      self.where(actif: true).each do |p|
        prov = {}
        prova = {}
        meta_missing = {}
        creator = {}
        client.query("SELECT distinct mtpa_id, mtpa_param2, mtpa_param3, mtpa_param4, mtpa_param6, mtpa_created_at FROM MessageToPA where mtpa_done = 0 and mtpa_param1 = '#{p.string_key}' and mtpa_message='1' and mtpa_created_at > '#{ddeb}' and mtpa_created_at < '#{dfin}' and mtpa_param3 not in (11,15,16,18,19,20) order by mtpa_param3").each do |row|
          dec = row["mtpa_created_at"].formatted_offset.to_i
          prov[row['mtpa_param4']] = [row['mtpa_param3'].to_i, (row["mtpa_created_at"]+dec.hour).strftime("%H:%M:%S")]
          if p.is_pixtech_stock?
            #img_creator = Image.where(ms_image_id: row['mtpa_param2'].to_i).pluck(:creator).first
            begin
              img_creator = Image.where(ms_image_id: row['mtpa_param2'].to_i).pluck(:creator).first
            rescue RangeError
              img_creator = nil
            end
            creator[row['mtpa_param4']] = img_creator unless img_creator.nil?
          end
          if row['mtpa_param3'].to_i == 6
            begin
              meta_missing[row['mtpa_param4']] = row['mtpa_param6'].to_i
            rescue
              meta_missing[row['mtpa_param4']] = 0
            end
          end
        end
        client.query("SELECT distinct mtpa_id, mtpa_param2, mtpa_param3, mtpa_param4, mtpa_param6, mtpa_created_at FROM MessageToPA where mtpa_done = 0 and mtpa_param1 = '#{p.string_key}' and mtpa_message='1' and mtpa_created_at > '#{ddeb}' and mtpa_created_at < '#{dfin}' and mtpa_param3 in (11,15,16,18,19,20) order by mtpa_param3,mtpa_param6").each do |row|
          dec = row["mtpa_created_at"].formatted_offset.to_i
          prova[row['mtpa_param4']] = [row['mtpa_param3'].to_i, (row["mtpa_created_at"]+dec.hour).strftime("%H:%M:%S")]
          if p.is_pixtech_stock?
            #img_creator = Image.where(ms_image_id: row['mtpa_param2'].to_i).pluck(:creator).first
            begin
              img_creator = Image.where(ms_image_id: row['mtpa_param2'].to_i).pluck(:creator).first
            rescue RangeError
              img_creator = nil
            end
            creator[row['mtpa_param4']] = img_creator unless img_creator.nil?
          end
          if row['mtpa_param3'].to_i == 18
            begin
              meta_missing[row['mtpa_param4']] = row['mtpa_param6'].to_i
            rescue
              meta_missing[row['mtpa_param4']] = 0
            end
          end
        end
        unless prov.empty? && prova.empty?
          mel = ProviderContact.where(provider_id: p.id, receive_errors: true).collect{|pc| pc.email}
          UserMailer.ch_controls(mel, p.name, prov, prova, meta_missing, creator, p.get_pixtech_name, p.get_stock_name, p.is_pixtech_author?, p.is_pixtech_stock?, reference_date).deliver_now
          sleep 10
        end
      end
      client.close
    end
  end

  def self.alert_old_images
    # Send mail alert
    if Server.itself?(PIXADMIN_SERVER_NAME)
      self.where('days_keep_alert IS NOT NULL').each do |p|
        if p.days_keep_per_picture
          nb_imgs = Image.search_count with:{provider_id: p.id, updated_at: 0..(Time.now-(p.days_keep_alert+1).days).to_i, erasable: true, content_error: false, private_image: false}
        else
          nb_imgs = Image.search_count with:{provider_id: p.id, updated_at: 0..(Time.now-(p.days_keep_alert+1).days).to_i, content_error: false, private_image: false}
        end
        if nb_imgs > 0
          to_addr = ProviderContact.where(provider_id:p.id,receive_alert: 1).collect{|pc| pc.email}
          if to_addr.blank?
            puts "***** Agence #{p.name} - old_images alert mail not sent, no recipient --- #{Time.now}"
          else
            UserMailer.pictures_limit_alert(to_addr, p.name, 'days_keep', p.days_keep_alert, nb_imgs, p.days_keep).deliver_now
            puts "***** Agence #{p.name} - old_images alert mail sent --- #{Time.now}"
          end
        end
      end
    end
  end

  def self.delete_old_images(prov=nil)
    # Transfer pictures to PP2
    query_content = prov.nil? ? 'days_keep IS NOT NULL' : "days_keep IS NOT NULL and string_key = '#{prov}'"
    self.where(query_content).each do |p|
      # Get 10 000 first pictures to delete (Sphinx limitation)
      if p.days_keep_per_picture
        imgs = Image.search with:{provider_id: p.id, updated_at: 0..(Time.now-(p.days_keep+1).days).to_i, erasable: true, content_error: false, private_image: false}, order: :updated_at, per_page: 10000
      else
        imgs = Image.search with:{provider_id: p.id, updated_at: 0..(Time.now-(p.days_keep+1).days).to_i, content_error: false, private_image: false}, order: :updated_at, per_page: 10000
      end
      if imgs.count > 0
        STDOUT.sync = true
        warn_msg = "(10 000 images maximum will be processed)" if imgs.count > 10000
        puts "***** Provider #{p.name} - #{imgs.count} images to delete #{warn_msg} --- #{Time.now}"
        if Server.itself?(PIXADMIN_SERVER_NAME)
          # Send pictures to PP2 temp folder on MS
          # by FTP
          ftp_config = YAML.load_file(File.join(Rails.root, 'config', 'ftp.yml'))
          ftp = Net::FTP.new(ftp_config[:ms][:host],ftp_config[:ms][:temp_access][:user], ftp_config[:ms][:temp_access][:passwd])
          ftp.passive = ftp_config[:ms][:passive]
          ftp.chdir('PP2')
          # by SCP
          # Dir.mkdir(PP2_SCP_LOCAL_FOLDER) unless File.exists?(PP2_SCP_LOCAL_FOLDER)
          imgs.each do |i|
            # Find image with activerecord to get all fields
            im = Image.find(i.id)
            # Do not process pictures coming from controls or requests
            file = "public#{im.medium_location}"
            # check if agency prefix is follow by one dot, if not replace by one dot - For old file names with underscore like Andia files
            file_name = im.file_name
            string_key_sep = file_name.upcase.partition(p.string_key.upcase)[2][0]
            file_name = p.string_key + '.' + file_name.upcase.partition(p.string_key.upcase+string_key_sep)[2] if string_key_sep!='.'
            begin
              unless (im.hires_location.include? '/usr/PPserver/PA_only') || !p.actif || !File.exists?(file)
                ftp.putbinaryfile(file, file_name)
                DELETE_LOG.info("#{Time.now.to_s} : #{file_name} sent to FTP in PP2 folder")
                # FileUtils.cp(file, File.join(PP2_SCP_LOCAL_FOLDER,file_name))
                # DELETE_LOG.info("#{Time.now.to_s} : #{file_name} copied to PP2 folder (#{PP2_SCP_LOCAL_FOLDER})")
              end
              begin
                if Statistic.where(image_id: im.id).blank?
                  (im.hires_location.include? '/usr/PPserver/PA_only') ?  im.delete_hr : im.moved_to_pp2
                else
                  i.deletion_for_stats(true)
                end
              rescue Exception => e
                puts "#{Time.now.to_s} : error #{e} : while destroying #{im.file_name}"
              end
            rescue Exception => e
              DELETE_LOG.error("#{Time.now.to_s} : error #{e} : while sending #{file_name} to FTP in PP2 folder. Image will not be deleted.")
              # DELETE_LOG.error("#{Time.now.to_s} - Error : #{e} while copying #{file_name} to PP2 folder (#{PP2_SCP_LOCAL_FOLDER}). Image will not be deleted.")
            end
          end
          ftp.close
        else
          imgs.each do |i|
            begin
              # Find image with activerecord to get all fields
              im = Image.find(i.id)
              if Server.itself?(PTREF_SERVER_NAME)
                im.delete_hr if Image.check_ptref(im)
              else
                if Statistic.where(image_id: im.id).blank?
                  im.delete_hr
                else
                  i.deletion_for_stats
                end
              end
            rescue Exception => e
              puts "#{Time.now.to_s} : error #{e} : while destroying #{im.file_name}"
            end
          end
        end
      end
    end
  end

  def self.alert_toomany_images
    # Send mail alert
    if Server.itself?(PIXADMIN_SERVER_NAME)
      self.where('toomany_limit_alert > 0').each do |p|
        if p.days_keep_per_picture
          nb_photos = Image.search_count with:{provider_id: p.id, erasable: true, content_error: false, private_image: false}
        else
          nb_photos = Image.search_count with:{provider_id: p.id, content_error: false, private_image: false}
        end
        nb_imgs = nb_photos - p.toomany_limit_alert
        if nb_imgs > 0
          to_addr = ProviderContact.where(provider_id:p.id,receive_alert: 1).collect{|pc| pc.email}
          if to_addr.blank?
            puts "***** Provider #{p.name} - toomany_limit alert mail not sent, no recipient --- #{Time.now}"
          else
            UserMailer.pictures_limit_alert(to_addr, p.name, 'toomany_limit', p.toomany_limit_alert, nb_photos, p.toomany_limit, nb_imgs).deliver_now
            puts "***** Provider #{p.name} - toomany_limit alert mail sent --- #{Time.now}"
          end
        end
      end
    end
  end

  def self.delete_toomany_images(prov=nil)
    # Transfer pictures to PP2
    query_content = prov.nil? ? 'toomany_limit > 0' : "toomany_limit > 0 and string_key = '#{prov}'"
    self.where(query_content).each do |p|
      # Get total number of pictures
      if p.days_keep_per_picture
        nb_photos = Image.search_count with:{provider_id: p.id, erasable: true, content_error: false, private_image: false}
      else
        nb_photos = Image.search_count with:{provider_id: p.id, content_error: false, private_image: false}
      end
      if nb_photos > p.toomany_limit
        nb_to_delete = nb_photos - p.toomany_limit
        if p.days_keep_per_picture
          imgs = Image.search with:{provider_id: p.id, erasable: true, content_error: false, private_image: false}, order: :updated_at, per_page: nb_to_delete
        else
          imgs = Image.search with:{provider_id: p.id, content_error: false, private_image: false}, order: :updated_at, per_page: nb_to_delete
        end
        STDOUT.sync = true
        warn_msg = "(10 000 images maximum will be processed)" if nb_to_delete > 10000
        puts "***** Provider #{p.name} - #{nb_to_delete} images to delete #{warn_msg} --- #{Time.now}"
        if Server.itself?(PIXADMIN_SERVER_NAME)
          # Send pictures to PP2 temp folder on MS
          # by FTP
          ftp_config = YAML.load_file(File.join(Rails.root, 'config', 'ftp.yml'))
          ftp = Net::FTP.new(ftp_config[:ms][:host],ftp_config[:ms][:temp_access][:user], ftp_config[:ms][:temp_access][:passwd])
          ftp.passive = ftp_config[:ms][:passive]
          ftp.chdir('PP2')
          # by SCP
          # Dir.mkdir(PP2_SCP_LOCAL_FOLDER) unless File.exists?(PP2_SCP_LOCAL_FOLDER)
          imgs.each do |i|
            # Find image with activerecord to get all fields
            im = Image.find(i.id)
            # Do not process pictures coming from controls or requests
            file = "public#{im.medium_location}"
            # check if agency prefix is follow by one dot, if not replace by one dot - For old file names with underscore like Andia files
            file_name = im.file_name
            string_key_sep = file_name.upcase.partition(p.string_key.upcase)[2][0]
            file_name = p.string_key + '.' + file_name.upcase.partition(p.string_key.upcase+string_key_sep)[2] if string_key_sep!='.'
            begin
              unless (im.hires_location.include? '/usr/PPserver/PA_only') || !p.actif || !File.exists?(file)
                ftp.putbinaryfile(file, file_name)
                DELETE_LOG.info("#{Time.now.to_s} : #{file_name} sent to FTP in PP2 folder")
                # FileUtils.cp(file, File.join(PP2_SCP_LOCAL_FOLDER,file_name))
                # DELETE_LOG.info("#{Time.now.to_s} : #{file_name} copied to PP2 folder (#{PP2_SCP_LOCAL_FOLDER})")
              end
              begin
                if Statistic.where(image_id: im.id).blank?
                  (im.hires_location.include? '/usr/PPserver/PA_only') ?  im.delete_hr : im.moved_to_pp2
                else
                  i.deletion_for_stats(true)
                end
              rescue Exception => e
                puts "#{Time.now.to_s} : error #{e} : while destroying #{im.file_name}"
              end
            rescue Exception => e
              DELETE_LOG.error("#{Time.now.to_s} : error #{e} : while sending #{file_name} to FTP in PP2 folder. Image will not be deleted.")
              # DELETE_LOG.error("#{Time.now.to_s} - Error : #{e} while copying #{file_name} to PP2 folder (#{PP2_SCP_LOCAL_FOLDER}). Image will not be deleted.")
            end
          end
          ftp.close
        else
          imgs.each do |i|
            # Find image with activerecord to get all fields
            im = Image.find(i.id)
            if Server.itself?(PTREF_SERVER_NAME)
              im.delete_hr if Image.check_ptref(im)
            else
              if Statistic.where(image_id: im.id).blank?
                im.delete_hr
              else
                i.deletion_for_stats
              end
            end
          end
        end
      end
    end
  end

  def self.delete_toomany_web_images
    self.where('max_web > 0').each do |p|
      nb_photos = Image.where('provider_id = ? and web_id < ?', p.id, 2).count.to_i
      if p.max_web < nb_photos
        imgs = []
        Image.where('provider_id = ? and web_id < ?', p.id, 2).order(:updated_at).limit(nb_photos - p.max_web).collect{|i| imgs << i}
        puts "***** Agence #{p.name} Nb photos web a effacer #{imgs.count}"

        imgs.each do |i|
          i.delete_hr if Image.check_ptref(i)
        end
      end
    end
  end

  def self.pictures_per_creator(prov_string_key,email)
    if Server.itself?(PIXADMIN_SERVER_NAME)
      prov = self.find_by(string_key: prov_string_key)
      if prov.nil?
        puts "No provider found with string_key '#{prov_string_key}'"
      else
        #creators = {}
        creators = Image.where(provider_id: prov.id, content_error: 0).order(:creator).group(:creator).count
        total = 0
        creators.each{|nb_photos| total += nb_photos[1]}
        UserMailer.pictures_per_creator(prov.name, email, total, creators).deliver_now
      end
    end
  end

  def add_authorization_to_group(permission_label_id, group_id)
    return false unless membership == title_provider_groups.find_by_title_provider_group_name_id(group_id)
    membership.authorizations << Authorization.new(:permission_label_id => permission_label_id)
  end

  def add_logo(filename, file)
    begin
      ext = filename.split('.')[-1].downcase
      raise 'not a jpeg' if ext.match(/jpg|jpeg|jpe/).nil?
      logo = Magick::Image.read(file).first.resize_to_fit(140, 45)
      logo.write("#{Rails.root}/public/images/providers/#{string_key}.jpg")
      update_attributes({:logo => "#{string_key}.jpg"})
      true
    rescue
      false
    end
  end

  def self.export_to_csv(providers, provider_word)
    export = ''
    export.encode!('UTF-8')
    CSV(export, {col_sep: ';'}) do |csv|
      keys = [ :first_name, :last_name, :email, :phone, :fax]
      additionnal_keys = [I18n.t(:site), I18n.t(:address)]
      csv << [I18n.t(provider_word, count: 1)] + keys.collect {|key| I18n.t(key)} + additionnal_keys
      providers.each do |p|
        prov_line = [p.address, p.zip_code, p.city, p.country].compact.join(', ')
        p.provider_contacts.each do |contact|
          contact_data = []
          contact_data << p.name
          keys.each {|k| contact_data << contact.send(k)}
          contact_data << p.site << prov_line
          csv << contact_data
        end
      end
    end
    export
  end

  def is_stock?
    provider_type_id == 1
  end

  def is_author?
    provider_type_id == 2
  end

  def is_pixtech?(pixtech_name = nil)
    if pixtech_name
      pixtech.nil? ? false : pixtech.name == pixtech_name
    else
      !pixtech.nil?
    end
  end

  def is_pixtech_author?(pixtech_name = nil)
    if pixtech_name
      pixtech.nil? ? false : (pixtech.name == pixtech_name && provider_type_id == 2)
    else
      pixtech.nil? ? false : provider_type_id == 2
    end
  end

  def is_pixtech_stock?(pixtech_name = nil)
    if pixtech_name
      pixtech.nil? ? false : (pixtech.name == pixtech_name && provider_type_id == 1)
    else
      pixtech.nil? ? false : provider_type_id == 1
    end
  end

  def get_stock_name
    Provider.find_by(string_key: self.pp_string_key).name rescue ''
  end

  def get_pixtech_name
    self.pixtech.name rescue nil
  end

end
