/*
 * JPA DAO Template
 *
 *
 * Takatuka - Template fuer JPA DAO
 *
 */

package de.ivu.elect.business.person.boundary;

import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.EntityNotFoundException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.ivu.elect.business.person.entity.Tag;
import de.ivu.elect.business.person.entity.TagUK;

public abstract class AbstractTagDAO extends de.ivu.elect.jee.entity.AbstractDAO<Tag,
        de.ivu.elect.business.person.entity.TagPK
    , TagUK> {

  private static final long serialVersionUID = 1L;

  private static final Logger LOG = LoggerFactory.getLogger(AbstractTagDAO.class);

  public AbstractTagDAO() {
    super();
  }

  public boolean isEntityWithPKPresent(
            de.ivu.elect.business.person.entity.TagPK
     pk) {
    if (pk != null && pk.getId() != null) {
      return findByPrimaryKey(pk) != null;
    }

    return false;
  }

  @Override
  public Tag findByPrimaryKey(
        de.ivu.elect.business.person.entity.TagPK
      pk) {
    if (pk != null && pk.getId() != null) {
      return findByPrimaryKey(pk.getId());
    }

    throw new IllegalArgumentException("PK oder PK.getId() ist null! [pk = " + pk + "]");
  }


  @Override
  protected Tag findByPrimaryKey(Long id) {
    if (id == null) {
      throw new IllegalArgumentException("ID ist null! [id = " + id + "]");
    }
  return getEntityManager().find(Tag.class, id, CACHE_PROPERTIES);
  }



     /**
      * Name: AllNoFlush<br>
      * Beschreibung: <br>
      * EJBQL: SELECT o FROM Tag o<br>
      * SQL: <br>
      */
     public java.util.List<Tag> findByAll() {
            long start = 0L;

            if (de.ivu.elect.business.system.control.LogQueries.LOG_QUERIES) {
               start = System.currentTimeMillis();
            }

    try {

            try {

          		  
                              return
                              getEntityManager().
                                createNamedQuery("TAG.All")
                                                            .getResultList();
                                        
                    
        } catch (NonUniqueResultException nure) {
    LOG.warn("Tag, findByAll - NonUniqueResultException, Parameter: "
    
        );
    throw nure;
        }

    } finally {
    if (de.ivu.elect.business.system.control.LogQueries.LOG_QUERIES) {
    LOG.info("Query: " + getClass().getName()+".findByAll(): "+(System.currentTimeMillis()-start)+ " ms");
    }
    }
     }

     /**
      * Name: MandantNoFlush<br>
      * Beschreibung: <br>
      * EJBQL: SELECT o FROM Tag o WHERE o.mandant = ?1<br>
      * SQL: <br>
      */
     public java.util.List<Tag> findByMandant( @javax.annotation.Nonnull de.ivu.elect.business.mandant.entity.Mandant mandant) {
            long start = 0L;

            if (de.ivu.elect.business.system.control.LogQueries.LOG_QUERIES) {
               start = System.currentTimeMillis();
            }

    try {

        int versuch = 0;
      while (true) {
        versuch++;
                try {

          		  			  de.ivu.elect.business.mandant.entity.Mandant mandantCheckedAndAttached =  checkAndAttach(mandant, de.ivu.elect.business.mandant.entity.Mandant.class, "mandant"); ;
		  
                              return
                              getEntityManager().
                                createNamedQuery("TAG.Mandant")
                              .setParameter(1, mandantCheckedAndAttached)
                                                                      .getResultList();
                                        
                    
        } catch (EntityNotFoundException enfe) {
      // ELECTMUC-2455
       if (de.ivu.elect.business.system.control.InvalidateCacheOnEntityNotFound.INVALIDATE_CACHE &&
       versuch < de.ivu.elect.business.system.control.InvalidateCacheOnEntityNotFound.MAX_VERSUCHE ) {
       LOG.warn("findByMandant - EntityNotFoundException: " +enfe.getMessage()+", Versuch: " +versuch+" - lösche Cache - wiederhole");
        try {
         de.ivu.elect.business.system.boundary.CacheResetSession.reset(getEntityManager());
        } catch (Exception e) {
          LOG.warn("Fehler beim Zurücksetzen des Cache: "+e.getMessage());

        }
       } else {
        throw enfe;
       }
           } catch (NonUniqueResultException nure) {
    LOG.warn("Tag, findByMandant - NonUniqueResultException, Parameter: "
           + ", mandant:'"+mandant+"'"
    
        );
    throw nure;
            }
            }

    } finally {
    if (de.ivu.elect.business.system.control.LogQueries.LOG_QUERIES) {
    LOG.info("Query: " + getClass().getName()+".findByMandant(): "+(System.currentTimeMillis()-start)+ " ms");
    }
    }
     }

     /**
      * Name: NameNormalisiertMandantNoFlush<br>
      * Beschreibung: <br>
      * EJBQL: SELECT o FROM Tag o WHERE o.nameNormalisiert = ?1 AND o.mandant = ?2<br>
      * SQL: <br>
      */
     public Tag findByNameNormalisiertMandant( @javax.annotation.Nonnull String nameNormalisiert,  @javax.annotation.Nonnull de.ivu.elect.business.mandant.entity.Mandant mandant) {
            long start = 0L;

            if (de.ivu.elect.business.system.control.LogQueries.LOG_QUERIES) {
               start = System.currentTimeMillis();
            }

    try {

        int versuch = 0;
      while (true) {
        versuch++;
                try {

          		  			  String nameNormalisiertCheckedAndAttached =  checkAndAttach(nameNormalisiert, String.class, "nameNormalisiert"); ;
		  			  de.ivu.elect.business.mandant.entity.Mandant mandantCheckedAndAttached =  checkAndAttach(mandant, de.ivu.elect.business.mandant.entity.Mandant.class, "mandant"); ;
		  
                              return
                    (Tag)
                              getEntityManager().
                                createNamedQuery("TAG.NameNormalisiertMandant")
                              .setParameter(1, nameNormalisiertCheckedAndAttached)
                                        .setParameter(2, mandantCheckedAndAttached)
                                                                      .getSingleResult();
                                        
                    
        } catch (EntityNotFoundException enfe) {
      // ELECTMUC-2455
       if (de.ivu.elect.business.system.control.InvalidateCacheOnEntityNotFound.INVALIDATE_CACHE &&
       versuch < de.ivu.elect.business.system.control.InvalidateCacheOnEntityNotFound.MAX_VERSUCHE ) {
       LOG.warn("findByNameNormalisiertMandant - EntityNotFoundException: " +enfe.getMessage()+", Versuch: " +versuch+" - lösche Cache - wiederhole");
        try {
         de.ivu.elect.business.system.boundary.CacheResetSession.reset(getEntityManager());
        } catch (Exception e) {
          LOG.warn("Fehler beim Zurücksetzen des Cache: "+e.getMessage());

        }
       } else {
        throw enfe;
       }
           } catch (NonUniqueResultException nure) {
    LOG.warn("Tag, findByNameNormalisiertMandant - NonUniqueResultException, Parameter: "
           + ", nameNormalisiert:'"+nameNormalisiert+"'"
           + ", mandant:'"+mandant+"'"
    
        );
    throw nure;
            }
            }

    } finally {
    if (de.ivu.elect.business.system.control.LogQueries.LOG_QUERIES) {
    LOG.info("Query: " + getClass().getName()+".findByNameNormalisiertMandant(): "+(System.currentTimeMillis()-start)+ " ms");
    }
    }
     }



  @Override
  public boolean isEntityWithUKPresent(de.ivu.elect.business.person.entity.TagUK uk) {
    try {
      return findByUK(uk) != null;
    } catch (javax.persistence.NoResultException nre) {
      return false;
    }
  }

  @Override
  public boolean isEntityWithUKHasPK(de.ivu.elect.business.person.entity.TagUK uk,
        de.ivu.elect.business.person.entity.TagPK
      pk

  ) {
    try {
      return findByUK(uk).getPk().equals(pk);
    } catch (NoResultException ignored) {
      // Do nothing - be happy.
    }
    return true;
  }

   public de.ivu.elect.business.person.entity.Tag findByUK(de.ivu.elect.business.person.entity.TagUK uk){

    try {
     return (de.ivu.elect.business.person.entity.Tag) getEntityManager().createNamedQuery("TAG.UK")
                  .setParameter(1, uk
                .getNameNormalisiert ()  
              )
             .setParameter(2, uk
                .getMandantUK ()  
                .getNummer ()  
              )
          .getSingleResult()
     ;
     } catch (NonUniqueResultException nure) {
        LOG.warn("Tag, findByUK - NonUniqueResultException, UK: " + uk);
        throw nure;
     }
  }
    
}