module Symphonia
  class User < ApplicationRecord
    self.table_name = 'users'

    include ModelAttributes

    register_query do
      add_attribute :login, :link
      add_attribute :name, :link, sort: %i(first_name last_name), default: true
      add_attribute :first_name
      add_attribute :last_name
      add_attribute :email, :mail, default: true
      add_attribute :status, :enum, filter: "select"
      add_attribute :admin, :boolean
      add_attribute :login_count
      add_attribute :last_login_ip
      add_attribute :last_login_at
    end

    acts_as_authentic do |config|
      config.crypto_provider = ::Authlogic::CryptoProviders::SCrypt
    end
    validates :password,
              confirmation: { if: :require_password? },
              length: {
                minimum: 8,
                if: :require_password?
              }

    include UserManagement

    attr_writer :password_confirmation

    has_and_belongs_to_many :preferences, foreign_key: 'user_id'

    belongs_to :edited_by, class_name: 'Symphonia::User', optional: true

    accepts_nested_attributes_for :preferences

    scope :recipients_for, ->(notification) { joins(:preferences).where(preferences: { name: notification, type: 'Symphonia::EmailPreference' }) }

    scope :like, ->(q) { t = arel_table; where(t[:email].matches("%#{q}%").or(t[:first_name].matches("%#{q}%").or(t[:last_name].matches("%#{q}%")))) }
    scope :admins, -> { where(admin: true) }

    alias_attribute :mail, :email

    # def form_path
    #   'symphonia/users/form'
    # end

    private

    def require_password?
      external_id.blank? && super
    end

    class Anonymous

      def id
        0
      end

      def name
        'Anonymous'
      end

      def login
        'anonymous'
      end

      def email
        'anonym@nothing'
      end

      def save
        false
      end

      def create
        false
      end

      def admin
        false
      end

      alias admin? admin

      def logged_in?
        false
      end

      def persistence_token
        nil
      end

      def language
        nil
      end

    end

  end

end