class NewSupplier
  include ActiveAttr::Model
  attr_accessor :current_employee
  attr_reader :employee, :supplier

  attribute :supplier_name
  attribute :email
  attribute :password
  attribute :password_confirmation

  without_current_employee = { unless: 'current_employee.present?' }
  without_employee = { unless: 'employee.present?' }
  validates :supplier_name, presence: true
  validates :email, email: without_current_employee
  validates :password, presence: without_current_employee, confirmation: without_employee

  validate :employee_uniqueness_or_existence
  validate :supplier_name_uniqueness

  def current_employee=(employee)
    @current_employee = @employee = employee
  end

  def save
    if valid?
      persist!
      true
    else
      false
    end
  end

  def existing_employee?
    return true if current_employee.present?
    return false unless email.present? and password.present?
    existing_employee = Employee.find_by_email email
    if existing_employee.try(:valid_password?, password)
      @employee = existing_employee
      return true
    end
    false
  end

  def new_supplier_name?
    Supplier.count_by_name(supplier_name).zero?
  end

  private

  def persist!
    @employee ||= current_employee
    @employee ||= Employee.new email: email, name: email.to_s.sub(/\@.*/, ''), password: password, password_confirmation: password_confirmation
    raise "Cannot create employee with #{attributes.inspect}" unless employee.save
    @supplier = Supplier.create name: supplier_name
    supplier.add_manager employee
  end

  def employee_uniqueness_or_existence
    return if current_employee.present?
    return if @employee = current_employee
    if Employee.count_by_email(email) > 0
      employee = Employee.find_by_email(email)
      # Login employee when valid password is given for signup
      if employee.valid_password? password
        @employee = employee
      else
        errors.add :email, :taken
      end
    end
  end

  def supplier_name_uniqueness
    return unless (current_employee.present? || @employee.present?) and supplier_name.present?
    current_suppliers = (current_employee || @employee).suppliers
    errors.add :supplier_name, 'You already have a supplier with that name' if current_suppliers.map(&:name).include? supplier_name
  end
end
