class Admin::ProvidersController < ApplicationController
  layout nil
  skip_before_filter :login_required


  def index
    @providers = Provider.where(provider_type_id: 1, local: false).order(:name)
    @local_providers = Provider.where(provider_type_id: 1, local: true).order(:name)
    @photographer_providers = Provider.where(provider_type_id: 2).order(:pixtech_id, :pp_string_key, :name)
  end

  def new
    @provider = Provider.new
    @provider.provider_contacts.build
    @image_fields = [[I18n.t('creator_iptc',creator_word: (I18n.t(session[:creator_word]))),:creator],[I18n.t(:headline),:headline],
                     [I18n.t(:description),:description],[I18n.t(:rights),:rights],[I18n.t(:credit),:credit],
                     [I18n.t('source',provider_word: I18n.t(session[:provider_word], count: 1)).capitalize,:source],
                     [I18n.t(:instructions),:instructions],[I18n.t(:state),:state],[I18n.t(:object_name),:title],
                     [I18n.t(:category),:category],[I18n.t(:supplemental_category),:supplemental_category],
                     [I18n.t(:original_filename),:original_filename],[I18n.t(:file_name,service_name:session[:service_name]),:file_name],
                     [I18n.t(:reportage),:reportage]]
    render layout: 'simple_provider', notice: flash[:notice]
  end

  def edit
    @provider = Provider.find(params[:id])
    @provider.provider_contacts.build
    @image_fields = [[I18n.t('creator_iptc',creator_word: (I18n.t(session[:creator_word]))),:creator],[I18n.t(:headline),:headline],
                     [I18n.t(:description),:description],[I18n.t(:rights),:rights],[I18n.t(:credit),:credit],
                     [I18n.t('source',provider_word: I18n.t(session[:provider_word], count: 1)).capitalize,:source],
                     [I18n.t(:instructions),:instructions],[I18n.t(:state),:state],[I18n.t(:object_name),:title],
                     [I18n.t(:category),:category],[I18n.t(:supplemental_category),:supplemental_category],
                     [I18n.t(:original_filename),:original_filename],[I18n.t(:file_name,service_name:session[:service_name]),:file_name],
                     [I18n.t(:reportage),:reportage]]
    @rec_rules = @provider.copyright_rule
    @copyright_symbol = @provider.copyright_symbol
    if @rec_rules
      @rec_rules = @rec_rules.split(" / ")
      @t_rules = @rec_rules.collect{|x| x if x=~ /{/ }.compact
      @c_rule = @rec_rules.last if (@rec_rules.length != @t_rules.length)
      @t_rules.collect!{ |cr| cr.delete("\#{:}")}
      @selected_rules = []
      @t_rules.collect do |rul|
        @image_fields.find do |f|
          if f[1]==rul.to_sym
            @selected_rules.push([f[0], rul])
          end
        end
      end
    end
  end

  def create
    if params[:button]
      redirect_to(admin_path(), notice: "Annulation demandée")
    else
      @provider = Provider.new(permitted_params)
      if @provider.save
        redirect_to(admin_path(), notice: I18n.t('successfully_updated'))
      else
        redirect_to(new_admin_provider_path(), notice: "Erreur création : #{@provider.errors.full_messages}")
      end
    end
  end

  def update
    if params[:button]
      redirect_to(admin_path(), notice: "Annulation demandée")
    else
      @provider = Provider.find(params[:id])
      if @provider.update_attributes(permitted_params)
        redirect_to(admin_path(), :notice => I18n.t('successfully_updated'))
      else
        redirect_to(admin_path(), :notice => "Erreur update : #{@provider.errors.full_messages}")
      end
    end
  end

  def destroy
    @provider = Provider.find(params[:id])
    @provider.destroy
  end

  def show
    @provider = Provider.find(params[:id])
    @full_copyright_rule = @provider.copyright_symbol ? "© #{@provider.copyright_rule}" : @provider.copyright_rule
    @reportage_field = 'Information accessible à partir de PixAdmin seulement'
    @metadata_type = 'Information accessible à partir de PixAdmin seulement'
    if Server.itself? PIXADMIN_SERVER_NAME
      begin
      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"])

      row = client.query("SELECT comrul_param3 FROM AgenciesRules JOIN Agences on Agences.id=AgenciesRules.comrul_agencyid where Agences.filePrefix='#{@provider.string_key}' and comrul_param1 = '2_121'")
      case row.count
      when 0
        @reportage_field = 'Aucune règle'
      when 1
        @reportage_field = row.first['comrul_param3']
      else
        @reportage_field = 'Régles multiples, contacter le support.'
      end

      row = client.query("SELECT useXMP FROM Agences where Agences.filePrefix='#{@provider.string_key}'")
      if row.first.blank?
        @metadata_type = 'Information non disponible'
      else
        case row.first['useXMP']
        when 0
          @metadata_type = 'IPTC'
        when 1
          @metadata_type = 'XMP'
        end
      end

      client.close

      rescue
        @metadata_type = 'Erreur lors de la connexion à la base de données du MS'
        @reportage_field = 'Erreur lors de la connexion à la base de données du MS'
        client.close if client
      end

    end
  end

  private

  def permitted_params
    params.require(:provider).permit!
  end

end
