package com.acme.model.domain.ad.filter;


import com.acme.model.domain.ad.entity.Employee;
import com.acme.structure.BaseFilter;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public class EmployeeFilter extends BaseFilter
{
    public EmployeeFilter(Object object)
    {
        super(object);
    }

    @Override
    public Query createQuery(EntityManager manager)
    {
        Employee employee = (Employee)object;
        StringBuilder queryString = new StringBuilder("\nFROM \n");
        queryString.append(employee.getEntityName()).append(" emp WHERE 1=1\n");

        if (!isNullOrEmpty(employee.getFirstName()))
            queryString.append("AND lower(emp.firstName) like :firstName \n");
        if (!isNullOrEmpty(employee.getLastName()))
            queryString.append("AND lower(emp.lastName) like :lastName \n");
        if (!isNull(employee.getIdentityId()))
            queryString.append("AND emp.identityId=:identityId \n");

        Query query = manager.createQuery(queryString.toString());
        if (!isNullOrEmpty(employee.getFirstName()))
            query.setParameter("firstName", employee.getFirstName().toLowerCase());
        if (!isNullOrEmpty(employee.getLastName()))
            query.setParameter("lastName", employee.getLastName().toLowerCase());
        if (!isNull(employee.getIdentityId()))
            query.setParameter("lastName", employee.getIdentityId());

        return query;
    }
}
