module JamRuby
  class RetailerInvitation < ActiveRecord::Base

    include HtmlSanitize
    html_sanitize strict: [:note]


    belongs_to :user, class_name: ::JamRuby::User
    belongs_to :retailer, class_name: ::JamRuby::Retailer

    validates :retailer, presence: true
    validates :email, email: true
    validates :invitation_code, presence: true
    validates :accepted, inclusion: {in: [true, false]}
    validates :first_name, presence: true
    validates :last_name, presence: true
    validate :retailer_has_name, on: :create

    before_validation(on: :create) do
      self.invitation_code = SecureRandom.urlsafe_base64 if self.invitation_code.nil?
    end

    def retailer_has_name
      if retailer && retailer.name.blank?
        errors.add(:retailer, "must have name")
      end
    end

    def self.index(retailer, params)
      limit = params[:per_page]
      limit ||= 100
      limit = limit.to_i

      query = RetailerInvitation.where(retailer_id: retailer.id)
      query = query.includes([:user, :retailer])
      query = query.order('created_at')
      query = query.where(accepted:false)


      current_page = params[:page].nil? ? 1 : params[:page].to_i
      next_page = current_page + 1

      # will_paginate gem
      query = query.paginate(:page => current_page, :per_page => limit)

      if query.length == 0 # no more results
        {query: query, next_page: nil}
      elsif query.length < limit # no more results
        {query: query, next_page: nil}
      else
        {query: query, next_page: next_page}
      end
    end


    def self.create(current_user, specified_retailer,  params)

      invitation = RetailerInvitation.new
      invitation.retailer = specified_retailer
      invitation.email = params[:email]
      invitation.first_name = params[:first_name]
      invitation.last_name = params[:last_name]

      if invitation.save
        invitation.send_invitation
      end
      invitation
    end


    def send_invitation
        UserMailer.invite_retailer_teacher(self).deliver_now
    end
    def generate_signup_url
        "#{APP_CONFIG.external_root_url}/retailer/#{retailer.id}/teacher?invitation_code=#{self.invitation_code}"
    end

    def delete
      self.destroy
    end

    def resend
      send_invitation
    end



  end
end
