# encoding:utf-8
module Spree
  class BoletoDocsController < Spree::BaseController
    before_filter :check_authorization
    before_filter :load_order
    respond_to :html, :image, :pdf

    layout "spree/layouts/print_layout"
    
    def index
      @boletos = []
      @order.boleto_docs.pending.each do |boleto_doc|
        @boletos << boleto_doc.payload
      end
      respond_to do |format|
        format.html
        format.pdf do
          formato = "pdf"
          headers['Content-Type']= PaymentMethod::BoletoMethod::FORMATS[formato]
          send_data Brcobranca::Boleto::Base.lote(@boletos), :filename => "boletos_#{@order.number}.#{formato}", :disposition => "attachment", :type => PaymentMethod::BoletoMethod::FORMATS[formato]
        end
      end
    end
    
    def show
      prefs                     = Spree::Boleto::Configuration.preferences.dup
      banco                     = prefs[:banco]
      prefs.delete(:banco)
      prefs.delete(:parcelas)
      prefs.delete(:formato)
      prefs.delete(:per_page)

      @boleto_doc               = @order.boleto_docs.find(params[:id])
      #@boleto                  = Brcobranca::Boleto::Itau.new
      @boleto                   = "Brcobranca::Boleto::#{banco}".constantize.new(prefs)
      #@boleto.documento_cedente = @order.bill_address.cnpj
      @boleto.valor             = @boleto_doc.amount

      @boleto.data_documento    = @boleto_doc.due_date
      @boleto.convenio          = 0
      @boleto.numero_documento  = params[:id]

      @boleto.sacado            = @order.name
      #@boleto.sacado           = @order.bill_address.firstname+' '+@order.bill_address.lastname



      @boleto.sacado_documento  = @order.id

      @boleto.sacado_endereco   = @order.bill_address.full_address
      #@boleto.sacado_endereco  = @order.bill_address.address1

  
      #respond_to do |format|
       # format.html
        #format.pdf do
        #  formato = "pdf"
        #  logger.info "ENTROUUUUUUUUUUUU 2.1"
        #  headers['Content-Type']= PaymentMethod::BoletoMethod::FORMATS[formato]
        #  logger.info "ENTROUUUUUUUUUUUU 2.2"
        #  send_data @boleto.to_pdf, :filename => "boleto_#{@boleto_doc.order.number}_#{@boleto_doc.id}.#{formato}" , :disposition => "attachment", :type => PaymentMethod::BoletoMethod::FORMATS[formato]
        #  logger.info "ENTROUUUUUUUUUUUU 2.3"
        #end
        #format.image do
          formato = "jpg"
          headers['Content-Type']= PaymentMethod::BoletoMethod::FORMATS[formato]
          send_data @boleto.to_jpg, :filename => "boleto_#{@boleto_doc.order.number}_#{@boleto_doc.id}.#{formato}" , :disposition => 'inline', :type => PaymentMethod::BoletoMethod::FORMATS[formato]
        #end
      #end
    end

    def current_order(create_order_if_necessary = false)
          return @current_order if @current_order
          if session[:order_id]
            current_order = Spree::Order.find_by_id_and_currency(session[:order_id], current_currency, :include => :adjustments)
            @current_order = current_order unless current_order.try(:completed?)
          end
          if create_order_if_necessary and (@current_order.nil? or @current_order.completed?)
            @current_order = Spree::Order.new(:currency => current_currency)
            before_save_new_order
            @current_order.save!
            after_save_new_order
          end
          if @current_order
            @current_order.last_ip_address = ip_address
            session[:order_id] = @current_order.id
            return @current_order
          end
    end
    
    private 
    def check_authorization
      session[:access_token] ||= params[:token]
      order = current_order || Spree::Order.find_by_number(params[:order_id])

      if order
        authorize! :edit, order, session[:access_token]
      else
        authorize! :create, Spree::Order
      end
    end
    
    def load_order
      @order = Spree::Order.find_by_number(params[:order_id])
    end
  end
end