var pic_template = '<td width="100px"><a height="100px" class="thumbnail text-center"><img  src="{source}" big_src="{big_src}" alt="Not Found"></a></td>';
var pic_template_old = '<td width="100px"><a height="100px" class="thumbnail text-center"><img  src="{source}" alt="Not Found"></a></td>';
var title_template='<td width="100px" date="{date}" class="date-pick text-center">{text}</td>';


function dateablePath(path) {
    //object containing the path and a function atDate to replace
    //%Y %m %d wildcards with a given value
    if(!(this instanceof dateablePath))return new dateablePath(path);
    this.path = path || '';
    return this;
}

dateablePath.prototype.atDate = function(year,month,day){
    if (!month){
        //we've been given either a single string or a datetime object, roll with that
        if (typeof year !== 'string') var dt = year.format('YYYY-MM-DD');
        year = dt.slice(0, 4);
        month = dt.slice(5, 7);
        day = dt.slice(8, 10);
    }
    return this.path.replace("%Y",year).replace("%m",month).replace("%d",day);

};


// Quicklooks archive class
function QuicklooksArchive(archive_info_url) {
    this.base_url = archive_info_url;
    this.data = null;
}

QuicklooksArchive.prototype.loadInfo = function() {
    var self = this;
    return $.ajax({
        //url: METOBS_API_URL + "/api/archive/info",
        url: this.base_url,
        type: "GET"
    }).then(function(data){
        // initialize our structure
        self.data = data;
        return data;
    });
};

QuicklooksArchive.prototype.getFancyProductName = function(site,inst,level,product) {
    var products = this.getProductUrlsAtLevel(site,inst,level);
    if(products[product].display_name)
        return products[product].display_name.split('(')[0];
    else
        return product;

};

QuicklooksArchive.prototype.getProductUrlsAtLevel = function(site, inst, level, product, thumbnail) {
    level = level || 'level_b1';
    //if a product is specified, return its specific quicklook url,
    //otherwise return the object with all products for the given level
    if (product) {
        //yay recursion
        var products = this.getProductUrlsAtLevel(site,inst,level);
        var product_fmt;
        if (!products[product])
            return dateablePath('');
        if (!products[product].thumbnail_pattern)
            product = products[product].preview_product;
        product_fmt = products[product];
        if (product_fmt)
            return dateablePath(product_fmt[(thumbnail)?'thumbnail_pattern':'pattern']);
        else
            return dateablePath('');
    } else {
        return this.data.sites[site].instruments[inst].levels[level].products;
    }
};

QuicklooksArchive.prototype.getPathToProducts = function(site,inst,level,version) {
    level = level || 'level_b1';
    version = version || 'version_00';
    return dateablePath(site+'/'+inst+'/'+level+'/'+version+'/%Y/%m/%d/');
};

var lastNDays = function(n,date){
    return _.map(_.range(n),(i)=>moment.utc(date).subtract(n-1-i,"days"));
};



function dayRange(date,date2) {
        dates = [];    
        date2 = date2.add(12,'hours');
        var i = 0;
        while (moment.utc(date).add(i,'days').isBefore(date2)) {
            dates.push(moment.utc(date).add(i,'days'));
            i++;
        }
        return dates;
}

var get_old_quicklook_url =function(inst, site, product,dt,is_thumbnail){
    year = dt.slice(0,4);
    month = dt.slice(5,7);
    product +=(product)?'.':'';
    var prefix=(site=='aoss')?'rig':'mendota';
    var url = site+'/'+inst+'/img/'+year+'/'+month+'/'+prefix+'_'+inst+'.'+product+dt;
    var suffix = (is_thumbnail)?'_tn.png':'.png';
    url0 = METOBS_API_URL+"/pub/cache/"+url+"_000000_115959"+suffix;
    url1 = METOBS_API_URL+"/pub/cache/"+url+"_120000_235959"+suffix;
    return [url0,url1];
};


function get_quicklook_url(inst, site, product, dt, is_thumbnail) {
    //dt is a moment object - convert to string
    if (QUICKLOOKS_FORMAT == 'old'){
        if (typeof dt !== 'string') dt = dt.format('YYYY-MM-DD');
        return get_old_quicklook_url(inst,site,product,dt,is_thumbnail);
    }else {
        var url = quicklookArchiveInfo.getPathToProducts(site,inst).atDate(dt);
        var fname = quicklookArchiveInfo.getProductUrlsAtLevel(site,inst,'level_b1',product,is_thumbnail).atDate(dt);
        return METOBS_API_URL + "/pub/cache/" + url + fname;
    }
}
//
// var get_GET_params = function(inst,site,product,dt){
//     if(typeof dt !== 'string') dt = dt.format('YYYY-MM-DD');
//     var url = 'detail?inst='+inst+'&site='+site+'&product='+product+'&dt='+dt;
// }
//
// var s2p_map = {
//     'air_temp':'td',
//     'dewpoint':'td',
//     'wind_speed':'windsp',
//     'wind_direction':'winddr',
//     'accum_precip':'precip',
//     'solar_flux':'flux',
//     'pressure':'press',
//     'chlorophyll':'chloro',
//     'phycocyanin':'phyco',
//     'water_temp':'watert',
//     'met':'met',
//     'meteorogram':'meteorogram',
// };
//
// var stream_to_product = function(stream){
//     return s2p_map[stream];
// }
//
// var ql_label_map = {
//     'td':'Air Temperature and Dewpoint',
//     'windsp':'Wind Speed',
//     'winddr':'Wind Direction',
//     'precip':'Precip&shy;itation',
//     'flux':'Solar Flux',
//     'press':'Pres&shy;sure',
//     'chloro':'Choloro&shy;phyll',
//     'phyco':'Phyco&shy;cyanin',
//     'watert':'Water Temperature',
//     'met':'Meteor&shy;ogram'
// };
// function product_to_label(product){
//     return ql_label_map[product];
// }

// global quicklook info (data loaded later by main page .loadInfo())
var quicklookArchiveInfo = new QuicklooksArchive(METOBS_API_URL + "/api/archive/info");