/* External Widget Customer File to include on a webpage */
/**
 * Hafas Widget Core Lib
 *
 */
hfsWidgetCore = {
  version: "1.0.0",
  jsResources: [
      {src: 'hafas_lib_core'},
      {src: 'hafas_webapp_config', useCustomerPath: true},
      {src: 'hafas_webapp_application_widgets'}
  ],
  layout: null,
  extendedPath: '',
  deprecation: null,
  priorities:{
    'tp':1000,
    'sq':900,
    'him':800,
    'events':700,
    'map':600
  },
  sanitize: function (string) {
    var div = document.createElement('div');
    div.innerHTML = string;
    return div.textContent;
  },
  HTMLDecode: function (html) {
    if (typeof html !== 'string') {
      return html;
    }
    html = html.replace(/&/g, '&amp;');
    html = html.replace(/</g, '&lt;');
    html = html.replace(/>/g, '&gt;');
    html = html.replace(/"/g, '&quot;');
    html = html.replace(/'/g, '&apos;');
    return html;
  },
  getUrlParameter: function (name, url) {
    var decodedValue = decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [null, ''])[1].replace(/\+/g, '%20')) || null; // sanitize
    if (decodedValue !== null) {
      return this.HTMLDecode(this.sanitize(decodedValue));
    }
    return null;
  },
  init: function() {
    var widgetCoreScript = document.querySelectorAll('script[src*="hafas-widget-core.' + hfsWidgetCore.version + '"]');

    if (widgetCoreScript.length === 0)
      return;

    var src = widgetCoreScript[0].src;

    var layout = this.getUrlParameter('L', src);
    if (layout) {
      this.layout = layout;
      this.extendedPath = 'customer/' + this.layout + '/';
    }

    var language = this.getUrlParameter('language', src);
    if (language) {
      this.language = language;
    }

    var currentTab = this.getUrlParameter('currentTab', src);
    if (currentTab) {
      this.currentTab = currentTab;
    }

    hfsWidgetCore.waPath = hfsWidgetCore.getWebAppBasePath(src);
    hfsWidgetCore.injectCSS();
    hfsWidgetCore.initJSResouces();
  },
  injectCSS: function(){
    var widgetCSS = document.createElement("link");
    widgetCSS.href = hfsWidgetCore.waPath + this.extendedPath + 'css/hafas_widget.css';
    widgetCSS.type = 'text/css';
    widgetCSS.rel = 'stylesheet';
    document.head.appendChild(widgetCSS);
  },
  initJSResouces: function(){
    if(hfsWidgetCore.jsResources.length > 0) {
      var jsFileName = hfsWidgetCore.jsResources[0];
      var jsResourcePath = hfsWidgetCore.waPath;

      // certain files need to be loaded from virtual client directory
      if (hfsWidgetCore.jsResources[0].useCustomerPath)
        jsResourcePath += this.extendedPath;

      var jsFile = jsResourcePath + 'js/' + hfsWidgetCore.jsResources[0].src + '.js';
      hfsWidgetCore.injectJS(jsFile);
    }else{
      if(typeof Hafas != 'undefined'){
        // Komponenten sind geladen und stehen zur Verfügung
        var widgetsFound = hfsWidgetCore.scanForWidgets();
        hfsWidgetCore.initWidgets(widgetsFound);
      }
    }
  },
  injectJS: function(file){
    var widgetJS = document.createElement("script");
    widgetJS.src = file;
    widgetJS.type = 'text/javascript';
    widgetJS.onload = function(){
      hfsWidgetCore.jsResources.shift();
      hfsWidgetCore.initJSResouces();
    };
    document.head.appendChild(widgetJS);
  },
  getWebAppBasePath: function(src){
    var idx = src.lastIndexOf('/');
    path = src.substring(0, idx + 1);
    path = path.substr(0, path.lastIndexOf('/staticfiles/') + 1);
    return path;
  },
  scanForWidgets: function(){
    var widgets = Hafas('[data-hfs-widget]',true);
    var getKeyRegExp = /data-hfs-widget-(\S+|.|\d+)/;
    var getSwitchesKeyRegExp = /data-hfs-widget-switches-(\S+|.|\d+)/;
    var widgetsProcessed = [];
    for(var w=0; w < widgets.length;w++){
      var tmpWidget = widgets[w];
      var tmpAttributes = tmpWidget.attributes;
      var tmpWidgetObject = {};
      var tmpWidgetApps = [];
      var tmpWidgetSwitches = [];


      for(var a = 0; a < tmpAttributes.length;a++){
        var currAttr = tmpAttributes[a];

        /* Allgemeine Switches suchen */
        var switchTest = currAttr.name.match(getSwitchesKeyRegExp);
        if(switchTest != null){
          var switchKey = switchTest[1];
          var switchObj = {};
          switchObj[switchKey] = currAttr.value;
          tmpWidgetSwitches.push(switchObj);
        }

        // Prüfen, ob Widget-relevantes Attribut
        if(currAttr.name.indexOf('data-hfs-widget') == 0){
          var regExMatch = currAttr.name.match(getKeyRegExp);
          // TODO Die Überprüfung auf Länge 4 muss unbedingt noch durch eine gescheite RegExp getauscht werden
          var testRegExp = /data-hfs-widget-((?:(?!-).)*)(?:(?:(?!-).)*)$/gm;
          var widgetRegExResult = testRegExp.exec(currAttr.name);
          if(widgetRegExResult != null) {
            var widgetKey = widgetRegExResult[1];
            var regTmpString = 'data-hfs-widget-' + widgetKey + '-(\\S+|.|\\d+)';
            var appSettingsRegExp = new RegExp(regTmpString);
            var config = {};
            for(var m=0; m < tmpAttributes.length;m++) {
              var appSettingsMatch = tmpAttributes[m].name.match(appSettingsRegExp);
              if(appSettingsMatch != null && appSettingsMatch.length > 1) {
                config[appSettingsMatch[1]] = tmpAttributes[m].value;
              }
            }
            tmpWidgetApps.push({id: widgetKey, config: config});
          }
        }
        if(currAttr.name == 'data-hfs-interface'){
          tmpWidgetObject["interface"] = tmpWidget.getAttribute("data-hfs-interface");
        }
        if(currAttr.name == 'data-hfs-connectors'){
          tmpWidgetObject["connectors"] = tmpWidget.getAttribute("data-hfs-connectors").split(",");
        }
      }
      tmpWidgetObject["container"] = tmpWidget;
      tmpWidgetObject["apps"] = tmpWidgetApps;
      tmpWidgetObject["switches"] = tmpWidgetSwitches;
      if(this.deprecation != null) {
        tmpWidgetObject["deprecation"] = this.deprecation;
      }
      tmpWidgetObject["apps"].sort(Hafas.bind(this.sortApps,this));
      widgetsProcessed.push(tmpWidgetObject);
    }
    return widgetsProcessed;
  },
  sortApps: function(a,b){
     return this.priorities[b.id] - this.priorities[a.id];
  },
  initWidgets: function(widgets){
    Hafas.Core.init({
      'external': true,
      'iframe': false,
      'launchWidgetMode': true,
      'widgets': widgets,
      'webappBasePath': hfsWidgetCore.waPath,
      'language': this.language,
      'currentTab': this.currentTab,
      'customer': this.layout
    });
  }
};
hfsWidgetCore.init();
