/**
 * Copyright (C) 2019 Patrik Dufresne Service Logiciel <info@patrikdufresne.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package com.planimod.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.patrikdufresne.managers.AbstractManager;
import com.patrikdufresne.managers.ManagerContext;
import com.patrikdufresne.managers.ManagerException;
import com.patrikdufresne.managers.Query;
import com.patrikdufresne.util.BidiMultiHashMap;
import com.patrikdufresne.util.BidiMultiMap;

/**
 * Object manager for product.
 * 
 * @author Patrik Dufresne
 */
public class ProductManager extends AbstractManager<Product> {

    public ProductManager(PlanimodManagers managers) {
        super(managers);
    }

    /**
     * This function is used to copy a given product.
     * 
     * @param product
     *            The original product
     * @throws ManagerException
     */
    public Product copy(final Product product) throws ManagerException {
        return getManagers().query(new Query<Product>() {
            @Override
            public Product run() throws ManagerException {
                Product newProduct = new Product();
                newProduct.setFamily(product.getFamily());
                newProduct.setName(product.getName());
                add(Arrays.asList(newProduct));

                /*
                 * Copy the productPositions
                 */
                List<ProductPosition> list = getManagers().getProductPositionManager().listByProduct(product);
                for (ProductPosition pp : list) {
                    // Proceed with a copy
                    ProductPosition newPp = new ProductPosition();
                    newPp.setProduct(newProduct);
                    newPp.setPosition(pp.getPosition());
                    newPp.setNumber(pp.getNumber());
                    getManagers().getProductPositionManager().add(Arrays.asList(newPp));
                }
                return newProduct;
            }
        });
    }

    /**
     * Return the managers
     * 
     * @return
     */
    @Override
    public PlanimodManagers getManagers() {
        return (PlanimodManagers) super.getManagers();
    }

    /**
     * Return a table of shift and Product entry
     * 
     * @param shifts
     * @throws ManagerException
     */
    public Collection<ProductEntry> listProductTable(final Collection<Product> products) throws ManagerException {

        return getManagers().query(new Query<List<ProductEntry>>() {

            @Override
            public List<ProductEntry> run() throws ManagerException {

                // Query database
                org.hibernate.Query query = ManagerContext.getDefaultSession().getNamedQuery("listProductTable");
                query.setParameterList("products", products);

                // Hash this data using a bidi-multi-map
                List<ProductEntry> table = new ArrayList<ProductEntry>();
                for (Object[] row : (List<Object[]>) query.list()) {
                    Product product = (Product) row[0];
                    Integer count = Integer.valueOf(((Long) row[1]).intValue());
                    table.add(new ProductEntry(product, count));
                }
                return table;
            }

        });

    }

    /**
     * Return a table of production event.
     * 
     * @param events
     * @return
     * @throws ManagerException
     */
    public Map<ProductionEvent, ProductEntry> listProductTableByProductionEvent(Collection<ProductionEvent> events) throws ManagerException {
        // Collect product.
        Set<Product> products = new HashSet<Product>();
        for (ProductionEvent e : events) {
            products.add(e.getProduct());
        }
        // Query table
        Collection<ProductEntry> entries = listProductTable(products);
        // Build the map
        Map<ProductionEvent, ProductEntry> table = new HashMap<ProductionEvent, ProductEntry>(events.size());
        for (ProductionEvent e : events) {
            for (ProductEntry entry : entries) {
                if (entry.getKey().equals(e.getProduct())) {
                    table.put(e, entry);
                    break;
                }
            }
        }
        return table;
    }

    /**
     * Return a table of shift and Product entry
     * 
     * @param shifts
     * @throws ManagerException
     */
    public BidiMultiMap<Shift, Entry<Product, Integer>> listProductTableByShifts(final Collection<Shift> shifts) throws ManagerException {

        return getManagers().query(new Query<BidiMultiMap<Shift, Entry<Product, Integer>>>() {

            @Override
            public BidiMultiMap<Shift, Entry<Product, Integer>> run() throws ManagerException {

                // Query database
                org.hibernate.Query query = ManagerContext.getDefaultSession().getNamedQuery("listProductTableByShifts");
                query.setParameterList("shifts", shifts);

                // Hash this data using a bidi-multi-map
                BidiMultiMap<Shift, Entry<Product, Integer>> table = new BidiMultiHashMap<Shift, Entry<Product, Integer>>();
                for (Object[] row : (List<Object[]>) query.list()) {
                    Shift shift = (Shift) row[0];
                    Product product = (Product) row[1];
                    Integer count = Integer.valueOf(((Long) row[2]).intValue());
                    table.put(shift, new ProductEntry(product, count));
                }
                return table;
            }

        });

    }

    @Override
    public Class<Product> objectClass() {
        return Product.class;
    }

    /**
     * Override default implementation to delete the product position too.
     */
    @Override
    protected void preRemoveObject(Product t) throws ManagerException {
        ManagerContext.getDefaultSession().refresh(t);
        // This implementation will remove associate ProductPosition object
        Collection<ProductPosition> pps = getManagers().getProductPositionManager().listByProduct(t);
        getManagers().getProductPositionManager().remove(pps);
    }
}
