/**
 * 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 static com.planimod.ui.Localized._;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.Transformer;
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.patrikdufresne.util.BidiMultiMap;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.Product;
import com.planimod.core.ProductionEvent;
import com.planimod.core.Shift;
import com.planimod.core.comparators.ProductComparators;

/**
 * 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;Shift, String&gt;
 * <p>
 * This implementation will regroup the product together.
 * 
 * @author Patrik Dufresne
 * 
 */
public class ShiftProductionEventObservableMap 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();
                }
            });
        }
    }

    private PlanimodManagers managers;

    private PrivateInterface privateInterface = new PrivateInterface();

    private IObservableSet shifts;

    /**
     * Create a new observable map to provide labels
     * 
     * @param shifts
     *            the list of shifts
     * @param productionEventsMap
     *            an observable map between the production events and number of required position.
     */
    public ShiftProductionEventObservableMap(PlanimodManagers managers, IObservableSet shifts) {
        super(Shift.class, String.class);
        this.managers = managers;
        this.shifts = shifts;
        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.shifts.size() == 0) {
            super.clear();
            return;
        }

        // Query the production events for known shifts.
        BidiMultiMap<Shift, Entry<Product, Integer>> table;
        try {
            table = this.managers.getProductManager().listProductTableByShifts(shifts);
        } catch (ManagerException e) {
            Policy.getLog().log(new Status(IStatus.ERROR, Policy.JFACE_DATABINDING, IStatus.OK, e.getMessage(), e));
            return;
        }

        Map<Shift, String> map = new HashMap<Shift, String>();
        for (Shift s : (Set<Shift>) this.shifts) {
            // Find all production event related to current shifts.
            int total = 0;
            StringBuilder buf = new StringBuilder();
            List<Entry<Product, Integer>> products = new ArrayList<Entry<Product, Integer>>(table.valueSet(s));
            Collections.sort(products, ComparatorUtils.transformedComparator(ProductComparators.byRefIdFamilyName(), new Transformer() {
                @Override
                public Object transform(Object arg0) {
                    return ((Entry<Product, Integer>) arg0).getKey();
                }
            }));
            for (Entry<Product, Integer> e : products) {
                ProductLabelObservableMap.format(buf, e.getKey(), e.getValue());
                total += e.getValue();
                buf.append("\r\n");
            }
            if (total > 0) {
                buf.append(_("Total: %d", total));
            }
            map.put(s, buf.toString());
        }
        // 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.shifts.addSetChangeListener(this.privateInterface);
    }

    @Override
    protected void lastListenerRemoved() {
        super.lastListenerRemoved();
        this.managers.removeObserver(ManagerEvent.ALL, ProductionEvent.class, this.privateInterface);
        this.shifts.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();
    }

}
