'use strict';

//
// this file contains just the implementation of the
// Observation class (I know there are no classes in javascript...)
//

function Observation(obj)
{
    if (typeof(obj)!='object')
        throw new Error("Observation object can only be constructed using an object.");

    if (!obj.date)
        throw new Error("Observation object must have a 'date' parameter");

    var ret = [];

    // FIXME: Check transisiton from summer- and winter-time!!
    var utc = new Date(obj.date);
    if (isNaN(utc.valueOf()))
        throw new Error(obj.date+' is not a valid Date String.'+
                        ' Try something like "2013-01-08 23:05 UTC" .');
    ret.start = utc;

    // If the given data is not an array, make it the first entry of an array
    // so that we can simply loop over all entries
    if (obj.measurements.length===undefined)
    {
        var cpy = obj.measurements;
        obj.measurements = [];
        obj.measurements[0] = cpy;
    }

    for (var i=0; i<obj.measurements.length; i++)
    {
        var obs = obj.measurements[i];

        ret[i] = { };
        ret[i].task   = obs.task ? obs.task.toUpperCase() : "DATA";
        ret[i].source = obs.source;
        ret[i].ra     = parseFloat(obs.ra);
        ret[i].dec    = parseFloat(obs.dec);
        ret[i].sub    = i;
        ret[i].start  = utc;

        ret[i].toString = function()
        {
            var rc = this.task;
            rc += "["+this.sub+"]";
            if (this.source)
                rc += ": " + this.source;
            //rc += " ["+this.start.toUTCString()+"]";
            return rc;
        }
    
        switch (ret[i].task)
        {
        case 'DATA':
            if (i!=obj.measurements.length-1)
                throw new Error("DATA must be the last in the list of measurements");
            if (ret[i].source == undefined)
                throw new Error("Observation must have either 'source' or 'task' " +
                                "if 'task' == 'data' it must have also have 'source' ");
            break;

        case 'STARTUP':
            if (ret[i].source != undefined)
                console.out("warning. Observation with task='startup' also has source defined");
            break;

        case 'SHUTDOWN':
            if (ret[i].source != undefined)
                console.out("warning. Observation with task='shutdown' also has source defined");
            break;

        case 'RATESCAN':
            if (ret[i].source == undefined && (ret[i].ra == undefined || ret[i].dec == undefined))
                throw new Error("Observation must have either 'source' or 'ra' & 'dec' " +
                                "if 'task' == 'ratescan'");
            break;

        default:
            throw new Error(" the task of this observation:"+this.task+
                            "is not implemented. use one of: DATA, STARTUP, SHUTDOWN, RATESCAN.");
        }
    }

    return ret;
}
