class Employee
  include SimplyStored::Couch
  include ActiveModel::SerializerSupport
  attr_reader :settings
  DEFAULT_SETTINGS = {
    'manager' => false,
    'active' => true,
    'color' => '#3a87ad'
  }
  DEFAULT_SETTINGS.each do |attribute, default_value|
    define_method(attribute) { settings.public_send attribute }
    define_method("#{attribute}=") do |value|
      is_dirty
      settings.set attribute, value
    end
    if default_value == true or default_value == false # boolean
      define_method(:"#{attribute}?"){ public_send attribute }
    end
  end

  #view :by_confirmation_token, key: :confirmation_token # devise confirmable
  devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable #, :registerable #, :confirmable
  property :unconfirmed_email

  property :name
  #property :email

  has_many :employee_shifts, dependent: :destroy
  view :by_email, key: :email

  class << self
    def count_by_email(email)
      database.view by_email(key: email, reduce: true)
    end
    def default_settings
      DEFAULT_SETTINGS
    end
  end

  def object_attributes
    attributes.merge(settings.as_json).merge("id" => id)
  end

  #validates :email, email: true
  has_and_belongs_to_many :suppliers, storing_keys: false
  has_many :orders
  has_and_belongs_to_many :lists, storing_keys: false

  def enrich_with_settings(settings)
    @settings = settings
    self
  end
  alias_method :settings=, :enrich_with_settings

  #alias_method :orig_save, :save
  #def save(*args)
    #settings.persist!
    #orig_save(*args)
  #end
  before_save { settings.persist! }

  def settings
    @settings || SupplierEmployeesSettings.new(Supplier.new).for_employee(self)
  end
end
