class Document < ActiveRecord::Base
  include Workflow

  belongs_to :accepted_offer

  before_create :generate_download_token
  before_create :set_default_fields_values

  has_one :customer, :through => :accepted_offer

  mount_uploader :document, DocumentUploader
  mount_uploader :returned_document, DocumentUploader

  acts_as_paranoid
  workflow_column :state

  validates :title, :presence => true


  workflow do
    state :not_available do
      event :upload_document, :transitions_to => :document_available
    end
    state :document_available do
      event :download_document, :transitions_to => :document_downloaded
    end
    state :document_downloaded do
      event :return_document, :transitions_to => :document_returned
    end
    state :document_returned do
      event :verify, :transitions_to => :document_verified
    end
    state :document_verified
  end

  def human_state
    case state
    when 'not_available'
      "Pas encore disponible, patientez..."
    when 'document_available'
      "Disponible"
    when 'document_downloaded'
      "Téléchargé, à retourner signé"
    when 'document_returned'
      "Retourné, en attente de vérification"
    when 'document_verified'
      "Retourné et vérifié"
    end
  end

  def human_admin_state
    case state
    when 'not_available'
      "Vous devez charger le document"
    when 'document_available'
      "Disponible et en attente de téléchargement par le client"
    when 'document_downloaded'
      "Téléchargé par le client, en attente de retour"
    when 'document_returned'
      "Retourné par le client, en attente de vérification"
    when 'document_verified'
      "Retourné et vérifié"
    end
  end

  def generate_download_token
    self.download_token = loop do
      download_token = SecureRandom.urlsafe_base64(nil, false)
      break download_token unless Document.exists?(download_token: download_token)
    end
  end

  def set_default_fields_values
    self.particulars = true
  end


  def get_particularized_document_file_path
    @temp_file = "#{Rails.root}/pdf/documents/#{self.id}_temp.pdf"
    @final_file = "#{Rails.root}/pdf/documents/#{self.id}.pdf"
    @final_file2 = "#{Rails.root}/pdf/documents/#{self.id}-2.pdf"


    view = ActionView::Base.new(Rails.root.join('app/views'))
    view.class.include ApplicationHelper
    view.class.include Rails.application.routes.url_helpers

    pdf = view.render(
            :pdf => "#{self.id}",
            :template => "public/documents/particulars.html.haml",

            :locals => {:@document => self})

    # then save to a file
    pdf = WickedPdf.new.pdf_from_string(pdf, :margin =>  {   top:               0,                     # default 10 (mm)
                                        bottom:            0,
                                        left:              0,
                                        right:             0 })

    save_path = @temp_file
    File.open(save_path, 'wb') do |file|
    file << pdf
    end



    require 'posix/spawn'

    ::POSIX::Spawn::Child.new 'pdftk', self.document.file.path, 'background',@temp_file , 'output',  @final_file

    ::POSIX::Spawn::Child.new 'pdftk', "A="+self.document.file.path, 'B='+@final_file ,"cat", "B1", "A2-end", 'output',  @final_file2

    @final_file2

  end

end
