class PartnersController < SecureController
  before_action :set_paper_trail_whodunnit
  def index
    if current_partner.admin
      render json: Partner.all.order(:name, :id)
    else
      render not_found
    end
  end

  def show
    partner = Partner.named params[:id]

    if (current_partner.admin and partner) or (current_partner == partner)
      render  json: partner,
              serializer: PartnerInfoSerializer
    else
      head :not_found
    end
  end

  def update
    if params[:change_password]
      partner = Partner.find_by_name params[:partner_name]

      begin
        partner.old_password = params[:current_password]
        partner.new_password = params[:new_password]

        response = partner.update_cocca_password

        render  json: response.to_json
      rescue Exception => e
        response = e.message
        render  json: response.to_json
      end

    elsif params[:cocca_update_password]
      partner = Partner.find_by_name params[:partner_name]

      if !partner.nil?
        partner.epp_partner            = true
        partner.password_sync_in_cocca = false
        partner.save
      end

      render status: 200, json: partner.to_json
    elsif params[:cocca_update_profile]
      partner = Partner.find_by_name params[:partner_name]

      if partner.update partner_params
        render  json: partner
      else
        render validation_failed partner
      end
    else
      partner = Partner.find params[:id]

      if partner
        update_partner partner
      else
        render not_found
      end
    end
  end

  def export_annual_transaction_to_csv
    year = params[:year].nil? ? Date.today.year : params[:year]
    ReportMailer.delay_for(2.seconds, queue: "registry_mailer").annual_transaction_to_csv year, current_partner
  end

  def has_transaction_for_year
    has_transaction = true
    year = params[:year].nil? ? Date.today.year : params[:year]

    orders  = current_partner.orders.where("extract(year from ordered_at) = ?", year)
    credits = current_partner.credits.where("extract(year from credited_at) = ?", year)

    if orders.empty? and credits.empty?
      has_transaction = false
    end

    render  json: {has_transaction: has_transaction}
  end

  private

  def update_partner partner
    if partner.update partner_params
      sync_update partner
      render  json: partner
    else
      render validation_failed partner
    end
  end

  def partner_params
    params.permit :name, :organization, :url, :nature, :representative, :position,
      :street, :city, :state, :postal_code, :country_code, :voice, :fax, :email
  end

  def sync_update partner
    ExternalRegistry.all.each do |registry|
      next if registry.name == 'troy'
      next if ExcludedPartner.exists? name: current_partner.name
      SyncUpdatePartnerProfileJob.perform_later registry.url, partner
    end
  end
end
