/*
 * 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.top;

import com.arrebol.taxiservicios.controller.connection.ConnectionManager;
import com.arrebol.taxiservicios.controller.util.HibernateUtil;
import com.arrebol.taxiservicios.model.core.User;
import java.io.Serializable;
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 Picasso
 */
public class PrivacyController extends ConnectionManager implements Serializable {

    /**
     * update the user password from UI.
     *
     * @param userId User identify number.
     * @param password Password to be updated.
     * @return true if password was update otherwise false.
     */
    public boolean updatePassword(String userId, String password) {
        logger.info("updatePassword");

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

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaUpdate<User> update = builder.createCriteriaUpdate(User.class);

            Root<User> root = update.from(User.class);

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

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

            if (1 == total) {
                logger.info("User updated: ");
                transaction.commit();

                success = true;
            } else {
                logger.error("User can not be updated ");
                rollback(transaction);
            }
        } catch (HibernateException e) {
            logger.error("User cannot be updated ", e);
            rollback(transaction);
        } catch (Exception e) {
            logger.error("Method updatePassword(userId" + userId + ") ", e);
            rollback(transaction);
        }
        return success;
    }

    private static final long serialVersionUID = -3407929995244086355L;

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

    public PrivacyController() {
    }

}
