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

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.databinding.observable.map.WritableMap;
import org.eclipse.core.databinding.observable.set.IObservableSet;
import org.eclipse.core.databinding.observable.set.ISetChangeListener;
import org.eclipse.core.databinding.observable.set.SetChangeEvent;
import org.eclipse.core.databinding.util.Policy;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import com.patrikdufresne.managers.IManagerObserver;
import com.patrikdufresne.managers.ManagerEvent;
import com.patrikdufresne.managers.ManagerException;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.Product;
import com.planimod.core.ProductEntry;
import com.planimod.core.ProductionEvent;
import com.planimod.core.Shift;

/**
 * This class provide an observable map between a shift object and a list of production events represented by a string.
 * i.e. This class is wrapping a Map&lt;Product, String&gt;
 * 
 * @author Patrik Dufresne
 * 
 */
public class ProductLabelObservableMap extends WritableMap {

    /**
     * Private interface to avoid exposing observers implementation.
     * 
     * @author Patrik Dufresne
     * 
     */
    private class PrivateInterface implements IManagerObserver, ISetChangeListener {

        /**
         * Public constructor
         */
        public PrivateInterface() {
            // Nothing to do
        }

        @Override
        public void handleManagerEvent(ManagerEvent event) {
            getRealm().exec(new Runnable() {
                @Override
                public void run() {
                    doCompute();
                }
            });
        }

        @Override
        public void handleSetChange(SetChangeEvent event) {
            getRealm().exec(new Runnable() {
                @Override
                public void run() {
                    doCompute();
                }
            });
        }
    }

    public static String format(Product product, Integer count) {
        return format(product, count, false);
    }

    public static String format(Product product, Integer count, boolean longLabel) {
        StringBuilder buf = new StringBuilder();
        format(buf, product, count, longLabel);
        return buf.toString();
    }

    public static void format(StringBuilder buf, Product product, Integer count) {
        format(buf, product, count, false);
    }

    /**
     * Used to format the product name.
     * 
     * @param buf
     *            a string builder
     * @param product
     *            the product
     * @param count
     *            the number of position in the product.
     */
    public static void format(StringBuilder buf, Product product, Integer count, boolean longlabel) {
        String family = product.getFamily() == null || product.getFamily().isEmpty() ? null : product.getFamily();
        String name = product.getName() == null || product.getName().isEmpty() ? null : product.getName();
        String refId = product.getRefId() == null || product.getRefId().isEmpty() ? null : product.getRefId();
        if (longlabel) {
            if (family != null) {
                buf.append(family);
                if (name != null || refId != null) {
                    buf.append(" - ");
                }
            }
            if (name != null) {
                buf.append(name);
                if (refId != null) {
                    buf.append(" - ");
                }
            }
            if (refId != null) {
                buf.append(refId);
            }
        } else {

            if (family != null) {
                buf.append(family);
                if (refId != null) {
                    buf.append(" - ");
                    buf.append(refId);
                }
            } else if (name != null) {
                buf.append(name);
                if (refId != null) {
                    buf.append(" - ");
                    buf.append(refId);
                }
            } else if (refId != null) {
                buf.append(refId);
            } else {
                buf.append("unknown");
            }
        }
        if (count != null) {
            buf.append(" (");
            buf.append(count);
            buf.append(")");
        }
    }

    /**
     * True to use the long label.
     */
    private boolean longLabel;

    private PlanimodManagers managers;

    private PrivateInterface privateInterface = new PrivateInterface();

    private IObservableSet products;

    /**
     * Create a new observable map to provide labels
     * 
     * @param products
     *            the list of shifts
     * @param productionEventsMap
     *            an observable map between the production events and number of required position.
     */
    public ProductLabelObservableMap(PlanimodManagers managers, IObservableSet products) {
        this(managers, products, false);
    }

    /**
     * Create a new observable map to provide labels
     * 
     * @param products
     *            the list of shifts
     * @param productionEventsMap
     *            an observable map between the production events and number of required position.
     */
    public ProductLabelObservableMap(PlanimodManagers managers, IObservableSet products, boolean longLabel) {
        super(Shift.class, String.class);
        this.managers = managers;
        this.products = products;
        this.longLabel = longLabel;
        doCompute();
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException();
    }

    /**
     * Make this observable map dirty.
     */
    protected void doCompute() {
        // If the shifts list is empty, clean the map.
        if (this.products.size() == 0) {
            super.clear();
            return;
        }

        // Query the production events for known shifts.
        Collection<ProductEntry> table;
        try {
            table = this.managers.getProductManager().listProductTable(this.products);
        } catch (ManagerException e) {
            Policy.getLog().log(new Status(IStatus.ERROR, Policy.JFACE_DATABINDING, IStatus.OK, e.getMessage(), e));
            return;
        }

        Map<Product, String> map = new HashMap<Product, String>();
        for (Entry<Product, Integer> e : table) {
            map.put(e.getKey(), ProductLabelObservableMap.format(e.getKey(), e.getValue(), this.longLabel));
        }
        // Update the map with new labels.
        super.putAll(map);

    }

    @Override
    protected void firstListenerAdded() {
        super.firstListenerAdded();
        this.managers.addObserver(ManagerEvent.ALL, ProductionEvent.class, this.privateInterface);
        this.products.addSetChangeListener(this.privateInterface);
    }

    @Override
    protected void lastListenerRemoved() {
        super.lastListenerRemoved();
        this.managers.removeObserver(ManagerEvent.ALL, ProductionEvent.class, this.privateInterface);
        this.products.removeSetChangeListener(this.privateInterface);
    }

    @Override
    public Object put(Object key, Object value) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(Map arg0) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object remove(Object key) {
        throw new UnsupportedOperationException();
    }

}
