//# sourceURL=jobs/WeatherController.js
/**
 * $Id: WeatherController.js 279 2017-10-28 22:33:19Z patrick $
 */
/* globals define,Controller */

define( [ 'entities/CurrentWeather', 'Controller' ], function( CurrentWeather, Controller ) {

    WeatherController = function( source ) {
        // console.log("Controller constructor! " + source);
        Controller.call( this, source );
        if ( "default" !== this.unit ) {
            this.baseurl = document.location.protocol + '//' + this.unit;
        } else {
            this.baseurl = document.location.protocol + '//' + document.location.hostname + ":8111";
        }
        console.log('weather baseurl is ' + this.baseurl);
    };

    WeatherController.prototype = Object.create(Controller.prototype);
    WeatherController.prototype.constructor = WeatherController;

    WeatherController.prototype.start = function() {
        var self = this;
        return new Promise( function( resolve, reject ) {
            self.run();
            resolve( self );
        });
    };

    WeatherController.prototype.run = function() {
        var self = this;
        for (var k in self.entities) {
            if ( self.entities.hasOwnProperty(k) && self.entities[k] instanceof CurrentWeather ) {
                new Promise( function( resolve, reject ) {
                    self.updateWeather( self.entities[k] );
                    resolve();
                }).catch( function( e ) {
                    util.warn(self.toString() + " failed weather update: " + String(e));
                });
            }
        }
        self.system.setAttributes( { state:true, error:false, lastupdate:new Date().getTime() } );
        self.startDelay(30 * 60000);
    };

    WeatherController.prototype.finalizeEntity = function( e ) {
        var self = this;
        return new Promise( function( resolve, reject ) {
            self.stop();
            self.run();
            resolve( e );
        });
    };

    WeatherController.prototype.updateWeather = function( entity ) {
        var self = this;
        var now = new Date().getTime();
        $.ajax({
            url: this.baseurl + '/api/weatherproxy',
            data: {
                "t" : self.subunit || "current",
                "unit": self.unit,
                "loc" : entity.getId(), /* Id is location for CurrentWeather entity */
                "force" : ( entity.getAttributeBoolean("force", false) ? 1 : 0 ),
                "now" : now
            },
            cache: false,
            dataType: "json"
        }).done( function( data ) {
            var cp = [ "N","NNE","NE","ENE","E","ESE","SE","SSE","S","SSW","SW","WSW","W","WNW","NW","NNW" ];
            var ws = { 0.3:"calm", 1.5:"light air", 3.3:"light breeze", 5.5:"gentle", 8:"moderate", 10.8:"fresh", 13.9:"strong", 17.2:"high", 24.5:"gale", 32.6:"storm", 999:"hurricane" };
            if (data.cod == 200) {
                entity.deferNotifies(true);
                entity.setAttribute("location", data.name);
                entity.setAttribute("timestamp", data.dt);
                entity.setAttribute("asoftime", new Date(data.dt*1000).toLocaleTimeString());
                entity.setAttribute("description", data.weather[0].main);
                entity.setAttribute("icon", data.weather[0].icon);
                entity.setAttribute("temperature", Math.round( data.main.temp * 9 / 5 - 459.67 ));
                entity.setAttribute("temp_lo", Math.round( data.main.temp_min * 9 / 5 - 459.67 ));
                entity.setAttribute("temp_hi", Math.round( data.main.temp_max * 9 / 5 - 459.67 ));
                entity.setAttribute("humidity", data.main.humidity);
                if ( data.rain ) {
                    var keez = util.sortByKey( data.rain );
                    entity.setAttribute("rainfall", (Math.round(data.rain[keez[0]] / .0254) / 100) + ' (' + keez[0] + ')');
                } else {
                    entity.setAttribute("rainfall", 0);
                }
                entity.setAttribute("windspeed", Math.round( data.wind.speed * 2.23694 ) ); // convert m/s to MPH
                var wd = data.wind.deg + 11.25;
                if (wd > 360) wd -= 360;
                wd = Math.floor( wd / 22.5 );
                entity.setAttribute("winddirection", cp[wd]);
                entity.setAttribute("barometer", Math.floor( data.main.pressure * 0.029529988 * 100 ) / 100 ); // hPa (hectopascals) to inHg (inches mercury)

                entity.setAttribute("lastupdate", now);
                entity.setAttribute("force", false);
                entity.deferNotifies( false );
            }
        }).fail( function() {
            throw new Error("getweather request failed")
        });
    };

    return WeatherController;

}); // define
