 class JamRuby::User

  attr_accessible :admin, :raw_password, :musician, :can_invite, :photo_url, :session_settings, :confirm_url, :teacher_attributes, :email_template, :is_platform_instructor, :admin_override_plan_code, :admin_override_ends_at, :admin_override_touch, :admin_override_reason, as: :admin # :invite_email

  attr_accessor :admin_override_touch
  accepts_nested_attributes_for :teacher, allow_destroy: true

  ransacker :jamuser_full_name, formatter: proc { |v| v.mb_chars.downcase.to_s } do |parent|
    Arel::Nodes::NamedFunction.new('LOWER',
                                   [Arel::Nodes::NamedFunction.new('concat_ws',
                                                                   [Arel::Nodes::SqlLiteral.new("' '"), User.arel_table[:first_name], User.arel_table[:last_name]])])
  end


  after_save :admin_override_handler_sync

  before_validation do
    if self.admin_override_plan_code == 'Remove Override'
      puts "Remove override just means set it to free again. so set to nil"
      self.admin_override_plan_code = nil
    end
  end

  def admin_override_handler_sync
    if admin_override_touch
      self.admin_override_touch = false
      @client = RecurlyClient.new
      # first, when ever we admin code it, set them to free. This would cancel any existing plan.  We don't want them geting charged in any scenario where we are doing this acitvity
      puts "Setting desired plan to free. Potentially cancelling existing."
      result, subscription, account = @client.update_desired_subscription(self, nil)

      self.update_admin_override_plan_code(self.admin_override_plan_code)
    end
  end
  def raw_password
    ''
  end

  def raw_password= pw
    unless pw.blank?
      # change_password(pw, pw)
      self.updating_password = true 
      self.password = pw
      self.password_confirmation = pw

      if au = self.admin_user
        au.update_attribute(:encrypted_password, self.password_digest)
      end
    end
  end


  def admin_user
    User.where(:email => self.email)[0]
  end

  def show_frame_options
    self.get_gear_mod(MOD_GEAR_FRAME_OPTIONS)
  end


  def how_to_use_video_no_show
    self.get_no_show_mod(HOWTO_USE_VIDEO_NOSHOW)
  end

  def configure_video_no_show
    self.get_no_show_mod(CONFIGURE_VIDEO_NOSHOW)
  end
end
