// vim: et:ts=4:sw=4:sts=4:ft=javascript

'use strict';

/*@
Ox.App <f> Basic application instance that communicates with a JSON API
    () ->              <f> App object
    (options) ->       <f> App object
    options <o> Options object
        timeout <n> request timeout
        type    <s> HTTP Request type, i.e. 'GET' or 'POST'
        url     <s> JSON API url
    self <o>    Shared private variable
    load <!>    app loaded
@*/

Ox.App = function(options) {

    var self = {
            options: Ox.extend({
                name: 'App',
                timeout: 60000,
                type: 'POST',
                url: '/api/'
            }, options || {}),
            time: new Date()
        },
        that = Ox.Element({}, Ox.extend({}, self));

    that.api = Ox.API({
        type: self.options.type,
        timeout: self.options.timeout,
        url: self.options.url
    }, function() {
        that.api.init(getUserData(), function(result) {
            //Ox.UI.hideLoadingScreen();
            that.triggerEvent({
                load: result.data
            });
        });
    });

    that.localStorage = Ox.localStorage(self.options.name);

    function getUserData() {
        return {
            document: {
                referrer: document.referrer
            },
            history: {
                length: history.length
            },
            location: {
                href: location.href
            },
            navigator: {
                cookieEnabled: navigator.cookieEnabled,
                plugins: Ox.makeArray(navigator.plugins).map(function(plugin) {
                    return plugin.name;
                }),
                userAgent: navigator.userAgent
            },
            screen: screen,
            time: (+new Date() - self.time) / 1000,
            window: {
                innerHeight: window.innerHeight,
                innerWidth: window.innerWidth,
                outerHeight: window.outerHeight,
                outerWidth: window.outerWidth,
                screenLeft: window.screenLeft,
                screenTop: window.screenTop
            }
        };
    }

    /*@
    change <f> change key/value
        (key, value) -> <u> currently not implemented
    @*/
    self.setOption = function(key, value) {
        
    };

    /*@
    options <f> get/set options, see Ox.getset
        () -> <o> get options
        (options) -> <o> update/set options
    @*/
    that.options = function() {
        return Ox.getset(self.options, Array.prototype.slice.call(arguments), self.change, that);
    };

    return that;

};