/**
 * 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.ui.views.admin.product;

import static com.planimod.ui.Localized._;

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

import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.Transformer;
import org.eclipse.nebula.paperclips.core.Print;
import org.eclipse.nebula.paperclips.core.border.LineBorder;
import org.eclipse.nebula.paperclips.core.grid.DefaultGridLook;
import org.eclipse.nebula.paperclips.core.grid.GridPrint;
import org.eclipse.nebula.paperclips.core.text.TextPrint;

import com.patrikdufresne.printing.FontDataUtil;
import com.planimod.core.Position;
import com.planimod.core.Product;
import com.planimod.core.ProductPosition;
import com.planimod.core.comparators.PositionComparators;
import com.planimod.core.comparators.ProductComparators;
import com.planimod.ui.printing.PlanimodPrintFactory;

/**
 * This class create a Employee Print Factory. It create a print listing employees.
 * 
 * @author patapouf
 * 
 */
public class ProductPositionPrintFactory extends PlanimodPrintFactory {

    private static class PositionCount {

        private int count;

        private Position position;

        public PositionCount(int count, Position position) {
            super();
            if (position == null) {
                throw new NullPointerException();
            }
            this.count = count;
            this.position = position;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) return true;
            if (obj == null) return false;
            if (getClass() != obj.getClass()) return false;
            PositionCount other = (PositionCount) obj;
            if (this.count != other.count) return false;
            if (!this.position.equals(other.position)) return false;
            return true;
        }

        public int getCount() {
            return this.count;
        }

        public Position getPosition() {
            return this.position;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + this.count;
            result = prime * result + this.position.hashCode();
            return result;
        }

    }

    /**
     * Annotation used to identify classified position.
     */
    private static final String ANNOTATION = "*";

    private static final String EMPTY = "";

    /**
     * Hold the list of product-position.
     */
    private Collection<ProductPosition> productPositions = null;

    /**
     * Create a new Factory.
     * 
     * @param jobName
     */
    public ProductPositionPrintFactory() {
        super(_("Produits - Postes"));
    }

    /**
     * This implementation create a employees print.
     */
    @Override
    protected Print createBodyArea() {

        if (this.productPositions == null) {
            return new TextPrint();
        }

        // Build the data to be printed.
        HashMap<Product, Set<PositionCount>> table = new HashMap<Product, Set<PositionCount>>();
        for (ProductPosition p : this.productPositions) {
            Set<PositionCount> set = table.get(p.getProduct());
            if (set == null) {
                set = new HashSet<PositionCount>();
                table.put(p.getProduct(), set);
            }
            set.add(new PositionCount(p.getNumber().intValue(), p.getPosition()));
        }
        HashMap<Set<PositionCount>, Set<Product>> tt = new HashMap<Set<PositionCount>, Set<Product>>();
        for (Entry<Product, Set<PositionCount>> e : table.entrySet()) {
            Set<Product> set = tt.get(e.getValue());
            if (set == null) {
                set = new HashSet<Product>();
                tt.put(e.getValue(), set);
            }
            set.add(e.getKey());
        }

        // Create a grid to hold all the Prints
        GridPrint topGrid = new GridPrint();
        topGrid.addColumn("c:d:g");

        // Create the title
        topGrid.add(new TextPrint(_("Liste des postes par produit"), FontDataUtil.HEADER1));

        GridPrint grid = new GridPrint();
        topGrid.add(grid);
        DefaultGridLook look = new DefaultGridLook();
        look.setCellBorder(new LineBorder());
        look.setCellPadding(5, 5);
        grid.setLook(look);
        grid.setCellClippingEnabled(false);
        grid.addColumn("l:d:g");
        grid.addColumn("l:d:g");
        grid.addHeader(new TextPrint(_("Produits"), FontDataUtil.BOLD));
        grid.addHeader(new TextPrint(_("Postes"), FontDataUtil.BOLD));

        List<Entry<Set<PositionCount>, Set<Product>>> entries = new ArrayList<Entry<Set<PositionCount>, Set<Product>>>(tt.entrySet());
        Collections.sort(entries, ComparatorUtils.transformedComparator(ProductComparators.byRefIdFamilyName(), new Transformer() {
            @Override
            public Object transform(Object input) {
                return Collections.min(((Entry<Set<PositionCount>, Set<Product>>) input).getValue(), ProductComparators.byRefIdFamilyName());
            }
        }));

        // Loop on employee's preference
        for (Entry<Set<PositionCount>, Set<Product>> e : entries) {

            grid.add(new TextPrint(getProductsText(e.getValue()), FontDataUtil.DEFAULT));
            grid.add(new TextPrint(getPositionsText(e.getKey()), FontDataUtil.DEFAULT));

        }

        return topGrid;
    }

    /**
     * Return a string representation of positions list.
     * 
     * @param s
     * @return
     */
    private String getPositionsText(Collection<PositionCount> s) {

        // Create a sorted list of product.
        List<PositionCount> list = new ArrayList<PositionCount>(s);
        Collections.sort(list, ComparatorUtils.transformedComparator(PositionComparators.byClassifiedName(), new Transformer() {
            @Override
            public Object transform(Object input) {
                return ((PositionCount) input).getPosition();
            }
        }));

        // Build the string.
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            PositionCount p = list.get(i);
            if (i > 0) {
                buf.append("\r\n");
            }

            String name = p.getPosition().getName() != null ? p.getPosition().getName() : EMPTY;
            name = p.getPosition().getClassified() ? name + ANNOTATION : name;

            buf.append(String.format("%d x %s", p.getCount(), name));

        }
        return buf.toString();
    }

    /**
     * Returns the list of product position to be printed.
     * 
     * @return production-positions or null if not set.
     */
    public Collection<ProductPosition> getProductPosition() {
        return this.productPositions;
    }

    /**
     * Return a string representing the list of product.
     * 
     * @param s
     *            the list of product.
     * @return a string
     */
    private String getProductsText(Collection<Product> s) {
        // Create a sorted list of product.
        List<Product> list = new ArrayList<Product>(s);
        Collections.sort(list, ProductComparators.byRefIdFamilyName());

        // Build the string.
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            Product p = list.get(i);
            if (i > 0) {
                buf.append("\r\n");
            }

            String name = p.getName() != null ? p.getName() : EMPTY;
            String refId = p.getRefId() != null ? p.getRefId() : EMPTY;

            if (p.getFamily() != null && !p.getFamily().isEmpty()) {
                buf.append(String.format("%s - %s - %s", refId, p.getFamily(), name));
            } else {
                buf.append(String.format("%s - %s", refId, name));
            }

        }
        return buf.toString();
    }

    /**
     * Sets the list of employees to print.
     * 
     * @param productPositions
     *            a list or null
     */
    public void setProductPosition(Collection<ProductPosition> productPositions) {
        this.productPositions = productPositions;
    }

}
