"use strict";
const EXPORTED_SYMBOLS = ["core", "resources"];
const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;
const resources = {
browser: {
styles: ["/native/fx/bindings.css"]}};
const WIDGET_NAME = "http://bar.yandex.ru/packages/yandexbar#cy";
const core = {
init: function CYWidget_init(api) {
this._api = api;
this._logger = api.logger;
this._loadModules();
api.Statistics.BarNavig.addDataProvider(barNavigDataProvider);
barNavigDataProvider._dataContainer = api.SysUtils.createDataContainer({
expirationTime: 2 * 60 * 60 * 1000});
this._REGION_REG = new RegExp(this.utils.utf8Tounicode("Регион: (.*)"), "g");
this._THEME_REG = new RegExp(this.utils.utf8Tounicode("^\\s*Тема:\\s*"), "");
}
,
finalize: function CYWidget_finalize() {
this._api.Statistics.BarNavig.removeDataProvider(barNavigDataProvider);
barNavigDataProvider._dataContainer.finalize();
barNavigDataProvider._dataContainer = null;
delete this.utils;
delete this._api;
delete this._logger;
}
,
buildWidget: function CYWidget_buildWidget(WIID, item) {
item.setAttribute("yb-native-widget-name",WIDGET_NAME);
item.setAttribute("yb-native-widget-wiid",WIID);
item.module = this;
}
,
destroyWidget: function CYWidget_destroyWidget(WIID, item, context) {
try {
if (typeof item.cyDestroy == "function")
item.cyDestroy();
}
 finally {
item.removeAttribute("yb-native-widget-name");
item.removeAttribute("yb-native-widget-wiid");
}

}
,
get API() {
return this._api;
}
,
gotoIndex: function CYWidget_gotoIndex(hostURL, event) {
this._navToCYPage(this._CY_URL + "host=" + encodeURIComponent(hostURL) + "&base=0",this._STAT_CODES.GOTO_INDEX,event);
}
,
gotoAllPages: function CYWidget_gotoAllPages(hostURL, event) {
var searchURL = this._api.Localization.createStringBundle("/urls/cy.properties").get("AllPagesSearchURL");
this._navToCYPage(searchURL + encodeURIComponent("host:" + hostURL),undefined,event);
}
,
getPref: function CYWidget_getPref(strPrefName, defaultValue) {
var prefFullName = this._api.Settings.getComponentBranchPath() + strPrefName;
var prefsModule = this._api.Settings.PrefsModule;
return prefsModule.get(prefFullName,defaultValue);
}
,
setPref: function CYWidget_setPref(strPrefName, strPrefValue) {
var prefFullName = this._api.Settings.getComponentBranchPath() + strPrefName;
var prefsModule = this._api.Settings.PrefsModule;
return prefsModule.set(prefFullName,strPrefValue);
}
,
_STAT_CODES: {
GOTO_INDEX: 3200,
GOTO_ALL_PAGES: 3510},
_MODULES: {
utils: "utils.jsm"},
_CY_URL: "http://www.yandex.ru/cy?",
_loadModules: function CYWidget__loadModules() {
var shAPI = this._api.shareableAPI;
for each(let [moduleName, moduleFileName] in Iterator(this._MODULES)) {
Cu.import(this._api.Package.resolvePath("/native/fx/modules/" + moduleFileName),this);
let module = this[moduleName];
if (typeof module.init == "function")
module.init(shAPI);
}

}
,
_navToCYPage: function CYWidget__navToCYPage(strURL, statAction, origEvent) {
if (statAction)
this.API.Statistics.logShortAction(statAction);
this.API.Controls.navigateBrowser({
url: strURL,
eventInfo: origEvent});
}
,
sendBarNavigRequest: function CYWidget_sendBarNavigRequest(aBrowser, aManual) {
var url = aBrowser.currentURI.spec;
var data = barNavigDataProvider._getData(url);
if (aManual && data.state !== this.DATA_STATE_REQUEST || data.state === this.DATA_STATE_UNKNOWN && aBrowser.contentDocument.readyState === "complete")
{
data.state = this.DATA_STATE_REQUEST;
this.API.Statistics.BarNavig.sendRequest({
url: url,
urlinfo: 1},barNavigDataProvider);
}
 else
{
this.updateToolbaritemData(aBrowser,url,data);
}

return data;
}
,
updateToolbaritemData: function CYWidget_updateToolbaritemData(aBrowser, aURL, aData) {
if (aBrowser)
{
this._updateToolbaritemDataInBrowser(aBrowser,aURL,aData);
return;
}

var wndEnum = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator).getEnumerator("navigator:browser");
while (wndEnum.hasMoreElements()) {
this._updateToolbaritemDataInBrowser(wndEnum.getNext().gBrowser.mCurrentBrowser,aURL,aData);
}

}
,
_updateToolbaritemDataInBrowser: function CYWidget__updateToolbaritemDataInBrowser(aBrowser, aURL, aData) {
var tabBrowser = "getTabBrowser" in aBrowser && aBrowser.getTabBrowser();
if (! (tabBrowser && tabBrowser.mCurrentBrowser === aBrowser))
return;
var currentURL = aBrowser.currentURI.spec;
if (currentURL === "about:blank")
currentURL = "";
if (currentURL.split("#")[0] !== aURL.split("#")[0])
return;
var toolbaritem = aBrowser.ownerDocument.querySelector("[yb-native-widget-name='" + WIDGET_NAME + "']");
if (! toolbaritem)
return;
if (! ("setCY" in toolbaritem))
return;
toolbaritem.setCY(aData);
}
};
const barNavigDataProvider = {
onWindowLocationChange: function CYWidget_BNDP_onWindowLocationChange(aParams) {
if (! aParams.windowListenerData.isCurrentTab)
return false;
var data = this._getData(aParams.url);
if (data.state === this.DATA_STATE_UNKNOWN && aParams.windowListenerData.readyState === "complete")
{
data.state = this.DATA_STATE_REQUEST;
aParams.barNavigParams.urlinfo |= 1;
core.updateToolbaritemData(aParams.browser,aParams.url,data);
return this;
}

core.updateToolbaritemData(aParams.browser,aParams.url,data);
return false;
}
,
onPageLoad: function CYWidget_BNDP_onPageLoad(aParams) {
if (! aParams.windowListenerData.isCurrentTab)
return false;
var data = this._getData(aParams.url);
if (data.isGoodURL)
{
data.state = this.DATA_STATE_REQUEST;
aParams.barNavigParams.urlinfo |= 1;
core.updateToolbaritemData(aParams.browser,aParams.url,data);
return this;
}

core.updateToolbaritemData(aParams.browser,aParams.url,data);
return false;
}
,
onBarNavigResponse: function CYWidget_BNDP_onBarNavigResponse(aParams) {
var url = aParams.url || aParams.barNavigParams.url;
var data = this._getData(url);
data.state = this.DATA_STATE_ERROR;
if (aParams.responseXML)
{
let urlinfo = aParams.responseXML.querySelector("urlinfo");
if (urlinfo)
{
let domain = urlinfo.querySelector("yaca[url]");
data.domain = domain && domain.getAttribute("url") || "";
let tcy = urlinfo.querySelector("tcy");
data.value = tcy && parseInt(tcy.getAttribute("value"),10) || 0;
data.rang = tcy && parseInt(tcy.getAttribute("rang"),10) || 0;
let titles = [];
Array.slice(urlinfo.querySelectorAll("topics > topic")).forEach(function (topic) {
var title = topic.getAttribute("title").replace(core._THEME_REG,"");
if (title)
titles.push(title);
}
);
data.theme = titles.join(", ");
let textinfo = urlinfo.querySelector("textinfo");
textinfo = textinfo && textinfo.textContent;
let region = textinfo && core._REGION_REG.exec(textinfo);
data.region = region && region[1] || null;
}

data.state = this.DATA_STATE_RESPONSE;
}

core.updateToolbaritemData(aParams.browser,url,data);
}
,
DATA_STATE_UNKNOWN: 1 << 0,
DATA_STATE_TIMED_REQUEST: 1 << 1,
DATA_STATE_REQUEST: 1 << 2,
DATA_STATE_ERROR: 1 << 3,
DATA_STATE_RESPONSE: 1 << 4,
_dataContainer: null,
get _emptyDataObject() {
return {
STATES: {
UNKNOWN: this.DATA_STATE_UNKNOWN,
TIMED_REQUEST: this.DATA_STATE_TIMED_REQUEST,
REQUEST: this.DATA_STATE_REQUEST,
ERROR: this.DATA_STATE_ERROR,
RESPONSE: this.DATA_STATE_RESPONSE},
domain: "",
value: 0,
rang: 0,
theme: "",
region: null};
}
,
_getData: function CYWidget_BNDP__getData(aURL) {
var data = aURL && this._dataContainer.get(aURL);
if (data)
return data;
data = this._emptyDataObject;
data.isGoodURL = aURL && /^https?:\/\//.test(aURL);
data.state = data.isGoodURL ? this.DATA_STATE_UNKNOWN : this.DATA_STATE_RESPONSE;
data.url = aURL;
return this._dataContainer.set(aURL,data).value;
}
};
