"use strict";
var EXPORTED_SYMBOLS = ["Service"];
var {Utils: Utils} = require("utils");
var {EngineManager: EngineManager} = require("engines");
var {Observers: Observers} = require("observers");
var {Auth: Auth} = require("auth");
var Service = {
init: function Service_init() {
onShutdown.add(this.finalize.bind(this));
require("wpage");
require("component");
this._engineManager = new EngineManager();
Observers.add("ybar:esync:auth:changed",this);
if (Auth && Auth.authorized)
this.enable();
}
,
finalize: function Service_finalize() {
Observers.notify("ybar:esync:plugin:disable");
Observers.remove("ybar:esync:auth:changed",this);
if (this.enabled)
this._stopChildren();
this._engineManager = null;
}
,
enable: function Service_enable() {
if (this._enabled)
return;
this._runChildren();
this._enabled = true;
Observers.notify("ybar:esync:service:ready");
}
,
disable: function Service_disable() {
if (! this._enabled)
return;
require("observers").Observers.notify("ybar:esync:service:disable");
this._stopChildren();
this._enabled = false;
}
,
get engineManager() {
return this._engineManager;
}
,
resetService: function Service_resetService() {

}
,
resetClient: function Service_resetClient(engines) {
try {
if (! engines)
{
this.resetService();
engines = this._engineManager.getAll();
}
 else
{
engines = this._engineManager.get(engines);
}

engines.forEach(function (engine) engine.resetClient());
}
catch (e) {
NativeAPI.logger.warn("Can not reset service client.");
NativeAPI.logger.debug(e);
}

}
,
observe: function Scheduler_observe(subject, topic, data) {
switch (topic) {
case "ybar:esync:auth:changed":
Auth.authorized ? this.enable() : this.disable();
break;
}

}
,
_runChildren: function Service__runChildren() {
require("xmpp").XMPP.init();
require("sync").Sync.init();
require("scheduler").Scheduler.init();
this._engineManager.init();
}
,
_stopChildren: function Service__stopChildren() {
this._engineManager.finalize();
require("scheduler").Scheduler.finalize();
require("sync").Sync.finalize();
require("xmpp").XMPP.finalize();
}
,
_freshStart: function Service__freshStart() {
this.resetClient();
}
,
get enabled() this._enabled,
_enabled: false,
_engineManager: null};
