include Devise::Models

module JamRuby
  class TextMessage < ActiveRecord::Base

    self.primary_key = 'id'

    default_scope { order('created_at DESC') }

    attr_accessible :target_user_id, :source_user_id, :message

    belongs_to :target_user, :class_name => "JamRuby::User", :foreign_key => "target_user_id"
    belongs_to :source_user, :class_name => "JamRuby::User", :foreign_key => "source_user_id"

    validate :same_school_protection
    def same_school_protection
      if source_user && target_user
        if !source_user.is_platform_instructor && !target_user.is_platform_instructor
          if source_user.school_id != target_user.school_id
            errors.add(:target_user, ValidationMessages::CAN_ONLY_CHAT_SAME_SCHOOL)
          end
        end
      end
    end

    validates :message, length: {minimum: 1, maximum: 400}, no_profanity: true

    def self.index(target_user_id, source_user_id, options = {})
      offset = options[:offset]
      limit = options[:limit]

      # if not specified, default offset to 0
      offset ||= 0
      offset = offset.to_i

      # if not specified, default limit to 10
      limit ||= 10
      limit = limit.to_i

      TextMessage
        .offset(offset)
        .limit(limit)
        .where('(source_user_id = (?) AND target_user_id = (?)) OR (source_user_id = (?) AND target_user_id = (?))', source_user_id, target_user_id, target_user_id, source_user_id)

    end

    def self.create(message, target_user_id, source_user_id)
      sanitized_text = Sanitize.fragment(message, elements: HtmlSanitize::SAFE)

      # create new message
      tm = TextMessage.new
      tm.message = sanitized_text
      tm.target_user_id = target_user_id
      tm.source_user_id = source_user_id
      tm.save

      # send notification
      @notification = Notification.send_text_message(sanitized_text, User.find(source_user_id), User.find(target_user_id))

      tm
    end
  end
end