/*
 * Copyright (C) 2009 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 *
 * This file is part of WSDDE.
 *
 * WSDDE is free software: it may be distributed and/or modified under
 * the terms of the GNU General Public License version 3 as published
 * by the Free Software Foundation and appearing in the file doc/gpl.txt
 * included in the packaging of this file.
 *
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

package wsdde;

import java.util.LinkedHashMap;
import java.util.Set;
/**
 *
 * This counter counts features. It remembers how many times a given feature was used in a context/corpus.  
 * 
 * @author Project Manager
 *
 */
public class Counter extends LinkedHashMap<String, Integer>{

	/**
	 * TODO: optimize this code! (used very often) 
	 */
	private static final long serialVersionUID = 4239588649153051734L;
	
	public void increase(String key,int about) {
		if (key==null) {return;}
		if (this.containsKey(key)) {
			int counter = this.get(key)+about;
			if (counter<1) {
				this.remove(key);
			} else {
				this.put(key, counter);
			}
		} else {
			this.put(key, about);
		}
	}
	
	public void increase(String key) {
		this.increase(key,1);
	}
	/**
	 * add to this counter another counter.
	 *  
	 * @param another counter to add
	 * @param presenceOnly if true only 1 is added (if string is present (any positive value))
	 */
	public void addCounter(Counter another, boolean presenceOnly) {
		Set<String> keys = another.keySet();
		for (String key : keys) {
			this.increase(key,(presenceOnly?1:another.get(key)));
		}
	}
	
	public void removeCounter(Counter another, boolean presenceOnly) {
		Set<String> keys = another.keySet();
		for (String key : keys) {
			this.increase(key,(presenceOnly?-1:-another.get(key)));
		}
	}

	
	
	
	
	//test only
	public static void main(String [] args) {
		Counter c1 = new Counter();
		c1.increase("rafał");
		c1.increase("rafał");
		c1.increase(null);
		Counter c2 = new Counter();
		c2.addCounter(c1,true);
		c1.increase("rafał");
		c2.increase("milena");
		c2.removeCounter(c1,false);
		c2.addCounter(c1,false);
		c2.increase("milena",9);
		c2.increase("kiełbasa",777);
		System.out.print("");
	}

}
