/**
 * Specialise WMSC.Control with functionality specific to the DDC.
 *
 * @author Stephen Pascoe
 */

DDC_Control = OpenLayers.Class.create();
Object.extend(DDC_Control.prototype, WMSC.Control.prototype);
Object.extend(DDC_Control.prototype, {
    _DIM_LAYERNAME_REGEXP: new RegExp('.*[^:]+_(\\d+)/'),
    _ISO_DATE_REGEXP: new RegExp('(\\d+)-(\\d+)-(\\d+)T(\\d+):(\\d+):(\\d+)\\.(\\d+)Z'),

    _MONTHS: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
	      'Sep', 'Oct', 'Nov', 'Dec'],

    // Override to render the time dimension better
    getDimensionText: function(dim, value) {
	var period;
	var report = this._deduceReport();

	if (dim.getName() != 'time') {
	    return value;
	}

	WMSC.log('In getDimensionText');
	// Deduce the averaging period
	// If it's TAR it will always be 30years
	if (report == 'tar') {
	    period = 30;
	}
	else {
	    try {
		period = this._getAveragingPeriod();
	    }
	    catch(err) {
		// Abord to default behaviour
		WMSC.log('Abording getDimensionText: '+ err);
		return value;
	    }
	}
	// Deconstruct the ISO8601 time value
	try {
	    var date = this._constructDate(value)
	}
	catch(err) {
	    // Abort to default behaviour
	    WMSC.log('Abording getDimensionText: '+ err);
	    return value;
	}

	// dy is the number of years to subtract from date to get
	// the start of the averaging period.
	var dy = (period / 2);


	return this._MONTHS[date.getMonth()] + ' ' + (date.getFullYear()-dy+1) + '-' + (date.getFullYear()-dy+period);
    },
    /**
     * This is done heuristically by examining the layer name.
     * @warning Reconfiguring the layer names will break this!
     */
    _getAveragingPeriod: function() {
	var layerName = this._selectedLayer.getName();
	var match = this._DIM_LAYERNAME_REGEXP.exec(layerName);
	WMSC.log('layername: '+layerName+', match: '+match);
	if (match == null) {
	    throw "No period found";
	}

	return Number(match[1]);
    },
    _constructDate: function(isoDate) {
	var match = this._ISO_DATE_REGEXP.exec(isoDate);
	WMSC.log('isoDate: '+isoDate+', match: '+match);
	if (match == null) {
	    throw "Date not recognised";
	}

	var date = new Date();
	date.setFullYear(Number(match[1]));
	date.setMonth(Number(match[2])-1);
	date.setDate(Number(match[3]));
	date.setHours(Number(match[4]));
	date.setMinutes(Number(match[5]));
	date.setSeconds(Number(match[6]));
	date.setMilliseconds(Number(match[7]));

	return date;
    },
    /**
     * Deduce which assessment report we are looking at.
     * @warning: this is a hack
     */
    _deduceReport: function() {
	if (this.wmsEndpoint.search('wms/tar') != -1) {
	    return 'tar';
	}
	else if (this.wmsEndpoint.search('wms/ar4') != -1) {
	    return 'ar4';
	}
	else if (this.wmsEndpoint.search('wms/obs') != -1) {
	    return 'obs';
	}
    }
});


    