/*
 * 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 com.arrebol.taxiservicios.controller.admin;

import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.admin.GeneralPublic;
import com.arrebol.taxiservicios.model.admin.SaleDetailGeneralPublic;
import com.arrebol.taxiservicios.model.admin.SaleGeneralPublic;
import com.arrebol.taxiservicios.model.core.User;
import com.arrebol.taxiservicios.model.enums.BasicType;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaUpdate;
import javax.persistence.criteria.Root;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Oscar
 */
public class GeneralPublicController extends ConnectionManager implements Serializable {
    
    public List<GeneralPublic> fillGeneralPublic() {
        logger.info("Searching all general public..");

        List<GeneralPublic> result = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            String query = "SELECT exp FROM GeneralPublic exp "
                    + "ORDER BY exp.createdOn DESC";

            result = session.createQuery(query).getResultList();

            transaction.commit();
            logger.info("Total of general public found: " + (null == result ? -1 : result.size()));
        } catch (HibernateException e) {
            logger.error("Can not load list of general public ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method fillGeneralPublic of general public", e);
            rollback(transaction);
        }

        return result;
    }
    
    public List<SaleGeneralPublic> findSaleForGeneralPublic(String idGeneral) {
        logger.info("findSaleForGeneralPublic");

        List<SaleGeneralPublic> results = null;
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();

            transaction = session.beginTransaction();

            results = session.createQuery("FROM SaleGeneralPublic WHERE generalPublic.id = :generalPublic ORDER BY createdOn")
                    .setParameter("generalPublic", idGeneral)
                    .getResultList();

            transaction.commit();

            logger.info("SaleGeneralPublic detail's list " + results.size());
        } catch (HibernateException e) {
            logger.error("Can not find SaleGeneralPublic details list", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findSaleForGeneralPublic()", e);
            rollback(transaction);
        }
        return results;
    }
    
    public List<SaleGeneralPublic> findSaleCreditForGeneralPublic() {
        logger.info("findSaleCreditForGeneralPublic");

        List<SaleGeneralPublic> results = null;
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();

            transaction = session.beginTransaction();

            results = session.createQuery("FROM SaleGeneralPublic WHERE typeSale = 'CREDIT' AND adeudo != 0 ORDER BY createdOn")
                    .getResultList();

            transaction.commit();

            logger.info("SaleGeneralPublic detail's list " + results.size());
        } catch (HibernateException e) {
            logger.error("Can not find SaleGeneralPublic details list", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method findSaleCreditForGeneralPublic()", e);
            rollback(transaction);
        }
        return results;
    }
    
    public boolean addGeneralPublic(GeneralPublic general) {
        logger.info("addGeneralPublic");

        boolean success = false;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            session.save(general);
            logger.info("GeneralPublic saved " + general.getId());
            transaction.commit();

            success = true;
        } catch (HibernateException e) {
            logger.error("GeneralPublic can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addGeneralPublic()", e);
            rollback(transaction);
        }
        return success;
    }
    
    public boolean addSaleGeneralPublic(SaleGeneralPublic sale) {
        logger.info("addSaleGeneralPublic");

        boolean success = false;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            session.save(sale);
            logger.info("SaleGeneralPublic saved " + sale.getId());
            transaction.commit();

            success = true;
        } catch (HibernateException e) {
            logger.error("SaleGeneralPublic can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addSaleGeneralPublic()", e);
            rollback(transaction);
        }
        return success;
    }
    
    public boolean addSaleDetailGeneralPublic(SaleDetailGeneralPublic general) {
        logger.info("addSaleDetailGeneralPublic");

        boolean success = false;

        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            session.save(general);
            logger.info("SaleDetailGeneralPublic saved " + general.getId());
            transaction.commit();

            success = true;
        } catch (HibernateException e) {
            logger.error("SaleDetailGeneralPublic can not be added ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method addSaleDetailGeneralPublic()", e);
            rollback(transaction);
        }
        return success;
    }
    
    public boolean updateGeneralPublicById(String id, BasicType status, User lastUpdatedBy) {
        logger.info("updateGeneralPublicById");

        boolean success = false;
        Transaction transaction = null;

        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();
            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaUpdate<GeneralPublic> query = builder.createCriteriaUpdate(GeneralPublic.class);
            Root<GeneralPublic> root = query.from(GeneralPublic.class);

            query.set(root.get("activeStatus"), status);
            query.set(root.get("lastUpdatedBy"), lastUpdatedBy);
            query.set(root.get("lastUpdatedOn"), new Date());

            query.where(builder.equal(root.get("id"), id));

            int total = session.createQuery(query).executeUpdate();

            if (1 == total) {
                transaction.commit();
                success = true;
                logger.info("Update GeneralPublic status successfully");
            } else {
                logger.info("CAN NOT update GeneralPublic");
                rollback(transaction);
            }
        } catch (HibernateException e) {
            logger.info("CAN NOT update GeneralPublic", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method updateGeneralPublicById()", e);
            rollback(transaction);
        }
        return success;
    }
    
    public GeneralPublic getById(String generalId) {
        logger.info("getById");

        GeneralPublic general = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            general = session.get(GeneralPublic.class, generalId);

            transaction.commit();
            logger.info("GeneralPublic " + general);
        } catch (HibernateException e) {
            logger.error("GeneralPublic cannot be loaded " + generalId, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getById(" + generalId + ") ", e);
            rollback(transaction);
        }
        return general;
    }
    
    public SaleGeneralPublic getByIdSaleGeneralPublic(String generalId) {
        logger.info("getByIdSaleGeneralPublic");

        SaleGeneralPublic general = null;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            general = session.get(SaleGeneralPublic.class, generalId);

            transaction.commit();
            logger.info("SaleGeneralPublic " + general);
        } catch (HibernateException e) {
            logger.error("SaleGeneralPublic cannot be loaded " + generalId, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method getByIdSaleGeneralPublic(" + generalId + ") ", e);
            rollback(transaction);
        }
        return general;
    }
    
    public boolean updateAdeudoById(GeneralPublic general, String id) {
        logger.info("updateAdeudoById");

        boolean success = false;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaUpdate<GeneralPublic> update = builder.createCriteriaUpdate(GeneralPublic.class);
            Root<GeneralPublic> root = update.from(GeneralPublic.class);
            
            update.set("adeudo", general.getAdeudo());
            update.set("km", general.getKm());
            update.set("kmMaintenance", general.getKmMaintenance());

            update.where(builder.equal(root.get("id"), id));

            int total = session.createQuery(update).executeUpdate();

            if (1 == total) {
                logger.info("GeneralPublic updated adeudo: " + id);
                transaction.commit();

                success = true;
            } else {
                logger.error("GeneralPublic can not be updated " + id);
                transaction.rollback();
            }
        } catch (HibernateException e) {
            logger.error("GeneralPublic cannot be updated " + id, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method updateAdeudoById(" + id + ") ", e);
            rollback(transaction);
        }
        return success;
    }
    
    public boolean updateAdeudoByIdSaleGeneralPublic(SaleGeneralPublic general, String id) {
        logger.info("updateAdeudoByIdSaleGeneralPublic");

        boolean success = false;
        Transaction transaction = null;
        try {
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            transaction = session.beginTransaction();

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaUpdate<SaleGeneralPublic> update = builder.createCriteriaUpdate(SaleGeneralPublic.class);
            Root<SaleGeneralPublic> root = update.from(SaleGeneralPublic.class);
            
            update.set("adeudo", general.getAdeudo());

            update.where(builder.equal(root.get("id"), id));

            int total = session.createQuery(update).executeUpdate();

            if (1 == total) {
                logger.info("SaleGeneralPublic updated adeudo: " + id);
                transaction.commit();

                success = true;
            } else {
                logger.error("SaleGeneralPublic can not be updated " + id);
                transaction.rollback();
            }
        } catch (HibernateException e) {
            logger.error("SaleGeneralPublic cannot be updated " + id, e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method updateAdeudoByIdSaleGeneralPublic(" + id + ") ", e);
            rollback(transaction);
        }
        return success;
    }
    
    private static final long serialVersionUID = -4436342523608482137L;

    final Logger logger = LogManager.getLogger(GeneralPublicController.class);

    public GeneralPublicController() {
    }
    
}
