/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package plate.wellmann.shop.persistence;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import org.apache.log4j.Logger;

/**
 *
 * @author Patrick
 */
@Entity
@NamedQueries({
    @NamedQuery(name = "UserDomain.findByName",
        query = "SELECT d FROM UserDomain d WHERE d.userDomain = :userDomain"),
    @NamedQuery(name = "UserDomain.findAll",
        query = "SELECT d FROM UserDomain d ")
})
public class UserDomain extends AbstractEntity{
   
     final static Logger logger = Logger.getLogger(UserDomain.class);
    
    @OneToMany(mappedBy = "userDomain")
    private List<Customer> customers;
    
    @Column(name="userDomain", unique=true, nullable=false)
    private final String userDomain;

    public UserDomain() {
        userDomain = null;
    }
    
    public UserDomain(String domain, Customer customer){
        this.userDomain = domain;
        customers = new ArrayList<>();
        customers.add(customer);
        logger.info("Created new UserDomain " + domain + " and added Costumer: " + customer.getEmail());
    }
    
    public void addCostumer(Customer customer){
        if(customers == null){
            customers = new ArrayList<>();
        }
        if (customer == null || customer == Customer.nullCustomer) {
            logger.warn("Tried to add null Customer to domain" + userDomain);
            return;
        }
        //to safe RAM
        //String domain = customer.getEmail().substring(customer.getEmail().indexOf("@") + 1);
        if (customer.getEmail().substring(customer.getEmail().indexOf("@") + 1).equals(userDomain)) {
            customers.add(customer);
            logger.info("Added " + customer.getEmail() + " to Domain " + userDomain);
        }
    }

    public List<Customer> getCustomers() {
        return customers;
    }

    public String getDomain() {
        return userDomain;
    }
}
