/*******************************************************************************
 * Copyright (c) 2013 Attila Kovacs <attila[AT]sigmyne.com>.
 * All rights reserved. 
 * 
 * This file is part of crush.
 * 
 *     crush is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     crush 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 General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with crush.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Attila Kovacs <attila[AT]sigmyne.com> - initial API and implementation
 ******************************************************************************/
package crush.telescope.apex;

import java.io.*;
import java.util.*;

import crush.CRUSH;
import jnum.Unit;
import jnum.Util;
import jnum.data.DataPoint;
import jnum.data.ScalarLocality;
import jnum.io.LineParser;
import jnum.text.SmartTokenizer;
import jnum.data.LocalAverage;
import jnum.data.Locality;
import jnum.data.LocalizedData;



public class APEXTauTable extends LocalAverage<APEXTauTable.Entry> {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7962217110619389946L;
	
	private static Hashtable<String, APEXTauTable> tables = new Hashtable<>();

	public String fileName;
	public double timeWindow = 1.5 * Unit.hour;
	

	
	private APEXTauTable(String fileName) throws IOException {
		read(fileName);
	}
	
	protected void read(String fileName) throws IOException {
		new LineParser() {
            @Override
            protected boolean parse(String line) throws Exception {
                SmartTokenizer tokens = new SmartTokenizer(line);
                Entry skydip = new Entry();
                tokens.skip(2);
                skydip.timeStamp = new TimeStamp(tokens.nextDouble());
                skydip.tau.setValue(tokens.nextDouble());
                skydip.tau.setRMS(1.0);
                add(skydip);
                return true;
            }   
		}.read(fileName);
		
		this.fileName = fileName;
		
		CRUSH.info(this, "[Loading tau data] -- " + size() + " values parsed.");
	}	
	
	public double getTau(double MJD) {
		Entry mean = getLocalAverage(new TimeStamp(MJD));
		
		if(mean.tau.weight() == 0.0) {
			CRUSH.info(this, "... No skydip data was found in specified time window.");
			
			if(timeWindow < 6.0 * Unit.hour) {
				CRUSH.info(this, "... expanding tau lookup window to 6 hours.");
				timeWindow = 6.0 * Unit.hour;
				mean = getLocalAverage(new TimeStamp(MJD));
			}
			else {
				CRUSH.warning(this, "Local tau is unknown.");
				return 0.0;
			}
		}
		else if(Double.isInfinite(mean.tau.value())) {
			CRUSH.warning(this, "Inifinite local tau.");
			return 0.0;
		}
		
		CRUSH.values(this, "Local average tau = " + Util.f3.format(mean.tau.value()) + " (from " + mean.measurements + " skydips)");
		return mean.tau.value();
	}
	
	class TimeStamp extends ScalarLocality {
		
		public TimeStamp(double MJD) { super(MJD); }
		
		@Override
		public double distanceTo(Locality other) {
			return super.distanceTo(other) * Unit.day / Math.abs(timeWindow);
		}
	}

	
	class Entry extends LocalizedData {
		/**
		 * 
		 */
		private static final long serialVersionUID = 3293214668641028650L;
		TimeStamp timeStamp;
		DataPoint tau = new DataPoint();
		
		
		@Override
		public Locality getLocality() {
			return timeStamp;
		}

		@Override
		public void setLocality(Locality loc) {
			timeStamp = (TimeStamp) loc;
		}

		@Override
		protected void averageWidth(LocalizedData other, Object env, double relativeWeight) {
			Entry entry = (Entry) other;
			tau.average(entry.tau.value(), relativeWeight * entry.tau.weight());
		}	
	}

	@Override
	public Entry getLocalizedDataInstance() {
		return new Entry();
	}
	
	public static APEXTauTable get(String fileName) throws IOException {
	    APEXTauTable table = tables.get(fileName);
	    if(table == null) {
	        table = new APEXTauTable(fileName);
	        tables.put(fileName, table);
	    }
	    return table;
	}

}

