/*******************************************************************************
* Copyright (c)                                                                *
*           2005   Tristan Allwood,                                            *
*           2005   Daniel Burke,                                               *
*           2005   Marc Hull,                                                  *
*           2005   Ekaterina Itskova,                                          *
*           2005   Steve Zymler                                                *
*                                                                              *
* Permission is hereby granted, free of charge, to any person obtaining a      *
* copy of this software and associated documentation files (the                *
* "Software"), to deal in the Software without restriction, including          *
* without limitation the rights to use, copy, modify, merge, publish,          *
* distribute, sublicense, and/or sell copies of the Software, and to           *
* permit persons to whom the Software is furnished to do so, subject to        *
* the following conditions:                                                    *
*                                                                              *
* The above copyright notice and this permission notice shall be included      *
* in all copies or substantial portions of the Software.                       *
*                                                                              *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS      *
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                   *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.       *
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY         *
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,         *
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE            *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                       *
*******************************************************************************/
/*
 * Created on Dec 25, 2004
 */
package uk.ac.ic.doc.kevlar.api.programs.framework.internal;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Manages writing to and flushing OutputStreams.
 * 
 * @author tora
 */
final class ToiletManager {

    private final PipeManager2 parent;

    private final Map<IPipeGroup, ToiletThread> managed;

    public ToiletManager(PipeManager2 parent) {
        this.parent = parent;
        this.managed = new HashMap<IPipeGroup, ToiletThread>();
    }

    void manageNewGroup(IPipeGroup group) {

        synchronized( managed ) {
            if( managed.containsKey(group)) {
                throw new IllegalArgumentException("Already managing that group");
            }
            ToiletThread t = new ToiletThread(group);
            managed.put(group,t);
            t.start();
        }
    }

    void writeOut(IPipeGroup group, IPacket data) {
        synchronized( managed ) {
            ToiletThread t = managed.get(group);
            t.eventQueue.add(data);
        }
    }

    void removeGroup(IPipeGroup group) {
        synchronized( managed ) {
            ToiletThread t = managed.remove(group);
            if( t == null ) { return; }
            
            t.stop.set(true);
            t.interrupt();
            
        }
    }

    class ToiletThread extends Thread {

        final BlockingQueue<IPacket> eventQueue;

        final Object lock = new Object();

        final AtomicBoolean stop;

        final IPipeGroup group;
        
        public ToiletThread(IPipeGroup group) {
            super("Toilet Thread");
            //setPriority(Thread.NORM_PRIORITY - 2);
            setDaemon(true);
            this.stop = new AtomicBoolean(false);
            this.group = group;
            this.eventQueue = new LinkedBlockingQueue<IPacket>();
        }

        public void run() {

            try {
                while (true) {
                    if (stop.get()) {
                        return;
                    }

                    IPacket packet = eventQueue.take();
                    
                    group.getOutputStream().writeObject(packet);
                    
                    while (!eventQueue.isEmpty()) {
                        packet = eventQueue.take();
                        group.getOutputStream().writeObject(packet);
                    }
                    
                    group.getOutputStream().flush();
                }

            } catch (InterruptedException e) {
                /* this is normal */
            } catch ( IOException ioe ) {
                parent.removeGroup(group);
            }

        }

    }
}
