module JamRuby
  class SchoolInvitation < ActiveRecord::Base

    include HtmlSanitize
    html_sanitize strict: [:note]


    belongs_to :user, class_name: ::JamRuby::User
    belongs_to :school, class_name: ::JamRuby::School

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

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

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

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

      query = SchoolInvitation.where(school_id: school.id)
      query = query.includes([:user, :school])
      query = query.order('created_at')
      query = query.where(as_teacher: params[:as_teacher])
      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_school,  params)

      invitation = SchoolInvitation.new
      invitation.school = specified_school
      invitation.as_teacher = params[:as_teacher]
      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
      if as_teacher
        UserMailer.invite_school_teacher(self).deliver_now
      else
        UserMailer.invite_school_student(self).deliver_now
      end
    end
    def generate_signup_url
      if as_teacher
        "#{APP_CONFIG.external_root_url}/school/#{school.id}/teacher?invitation_code=#{self.invitation_code}"
      else
        "#{APP_CONFIG.external_root_url}/school/#{school.id}/student?invitation_code=#{self.invitation_code}"
      end
    end

    def delete
      self.destroy
    end

    def resend
      send_invitation
    end



  end
end
