module JamRuby
  class School < ActiveRecord::Base

    include HtmlSanitize
    html_sanitize strict: [:name]

    GUITAR_CENTER = 'guitar_center'

    # the school will handle all communication with students when setting up a session
    SCHEDULING_COMM_SCHOOL = 'school'
    # the teacher will handle all communication with students when setting up a session
    SCHEDULING_COMM_TEACHER = 'teacher'
    SCHEDULING_COMMS = [ SCHEDULING_COMM_SCHOOL, SCHEDULING_COMM_TEACHER ]

    attr_accessor     :updating_avatar
    attr_accessible   :original_fpfile, :cropped_fpfile, :cropped_large_fpfile, :cropped_s3_path, :cropped_large_s3_path, :photo_url, :large_photo_url, :crop_selection

    belongs_to :user, class_name: ::JamRuby::User, inverse_of: :owned_school
    belongs_to :affiliate_partner, class_name: "JamRuby::AffiliatePartner"
    has_many :students, class_name: "JamRuby::User"
    has_many :teachers, class_name: "JamRuby::Teacher"
    has_many :school_invitations, class_name: 'JamRuby::SchoolInvitation'
    has_many :teacher_payments, class_name: 'JamRuby::TeacherPayment'
    has_many :teacher_distributions, class_name: 'JamRuby::TeacherDistribution'

    validates :user, presence: true
    validates :enabled, inclusion: {in: [true, false]}
    validates :education, inclusion: {in: [true, false]}
    validates :scheduling_communication, inclusion: {in: SCHEDULING_COMMS}
    validates :correspondence_email, email: true, allow_blank: true
    validate :validate_avatar_info

    after_create :create_affiliate
    #before_save :stringify_avatar_info, :if => :updating_avatar

    def self.autocreate_find_from_upload(school_name, school_tag)
      if school_name.blank?
        return nil
      end

      school = School.find_by_name(school_name)
      if school.nil?
        school = School.new
        school.name = school_name
        school.user = User.find_by_email('seth@jamkazam.com')
        school.school_tag = school_tag
        school.education = true
        school.save!
      end
      school
    end
    def is_education?
      education
    end

    def is_guitar_center?
      self.special == GUITAR_CENTER
    end

    def scheduling_comm?
      scheduling_communication == SCHEDULING_COMM_SCHOOL
    end

    def communication_email
      correspondence_email.blank? ? owner.email : correspondence_email
    end

    def approved_teachers
      teachers.where('teachers.ready_for_session_at is not null')
    end

    def create_affiliate
      AffiliatePartner.create_from_school(self)
    end
    def update_from_params(params)
      self.name = params[:name] if params[:name].present?
      self.scheduling_communication = params[:scheduling_communication] if params[:scheduling_communication].present?
      self.correspondence_email = params[:correspondence_email] if params[:correspondence_email].present?
      self.save
    end

    def owner
      user
    end

    def self.guitar_center
      School.find_by_special(GUITAR_CENTER)
    end

    def validate_avatar_info
      if updating_avatar
        # we want to mak sure that original_fpfile and cropped_fpfile seems like real fpfile info objects (i.e, json objects from filepicker.io)
        errors.add(:original_fpfile, ValidationMessages::INVALID_FPFILE) if self.original_fpfile.nil? || self.original_fpfile["key"].nil? || self.original_fpfile["url"].nil?
        errors.add(:cropped_fpfile, ValidationMessages::INVALID_FPFILE) if self.cropped_fpfile.nil? || self.cropped_fpfile["key"].nil? || self.cropped_fpfile["url"].nil?
        errors.add(:cropped_large_fpfile, ValidationMessages::INVALID_FPFILE) if self.cropped_large_fpfile.nil? || self.cropped_large_fpfile["key"].nil? || self.cropped_large_fpfile["url"].nil?
      end
    end

    def escape_filename(path)
      dir = File.dirname(path)
      file = File.basename(path)
      "#{dir}/#{ERB::Util.url_encode(file)}"
    end

    def update_avatar(original_fpfile, cropped_fpfile, cropped_large_fpfile, crop_selection, aws_bucket)
      self.updating_avatar = true

      cropped_s3_path = cropped_fpfile["key"]
      cropped_large_s3_path = cropped_large_fpfile["key"]

      self.update_attributes(
          :original_fpfile => original_fpfile.to_json,
          :cropped_fpfile => cropped_fpfile.to_json,
          :cropped_large_fpfile => cropped_large_fpfile.to_json,
          :cropped_s3_path => cropped_s3_path,
          :cropped_large_s3_path => cropped_large_s3_path,
          :crop_selection => crop_selection.to_json,
          :photo_url => S3Util.url(aws_bucket, escape_filename(cropped_s3_path), :secure => true),
          :large_photo_url => S3Util.url(aws_bucket, escape_filename(cropped_large_s3_path), :secure => true)
      )
    end

    def delete_avatar(aws_bucket)

      User.transaction do

        unless self.cropped_s3_path.nil?
          S3Util.delete(aws_bucket, File.dirname(self.cropped_s3_path) + '/cropped.jpg')
          S3Util.delete(aws_bucket, self.cropped_s3_path)
          S3Util.delete(aws_bucket, self.cropped_large_s3_path)
        end

        return self.update_attributes(
            :original_fpfile => nil,
            :cropped_fpfile => nil,
            :cropped_large_fpfile => nil,
            :cropped_s3_path => nil,
            :cropped_large_s3_path => nil,
            :photo_url => nil,
            :crop_selection => nil,
            :large_photo_url => nil
        )
      end
    end

    def stringify_avatar_info
      # fpfile comes in as a hash, which is a easy-to-use and validate form.  However, we store it as a VARCHAR,
      # so we need t oconvert it to JSON before storing it (otherwise it gets serialized as a ruby object)
      # later, when serving this data out to the REST API, we currently just leave it as a string and make a JSON capable
      # client parse  it, because it's very rare when it's needed at all
      self.original_fpfile = original_fpfile.to_json if !original_fpfile.nil?
      self.cropped_fpfile = cropped_fpfile.to_json if !cropped_fpfile.nil?
      self.crop_selection = crop_selection.to_json if !crop_selection.nil?
    end
  end

  def teacher_list_url
    "#{APP_CONFIG.external_root_url}/school/#{id}/teachers"
  end
end
