var themeManager = (function () {
  'use strict'; 
  var csInterface = new CSInterface();

  /* Convert the Color object to string in hexadecimal format; */
  function toHex(color, delta) {
    function computeValue(value, delta) {
      var computedValue = !isNaN(delta) ? value + delta : value;
      if (computedValue < 0) {
        computedValue = 0;
      } else if (computedValue > 255) {
        computedValue = 255;
      }            
      computedValue = Math.floor(computedValue);
      computedValue = computedValue.toString(16);
      return computedValue.length === 1 ? "0" + computedValue : computedValue;
    } 
    var hex = "";
    if (color) {
      hex = computeValue(color.red, delta) + computeValue(color.green, delta) + computeValue(color.blue, delta);
    }
    return hex;
  }

  //
  function insertRule(stylesheetId, selector, rule) {
    var stylesheet = document.getElementById(stylesheetId);   
    if (stylesheet) {
      stylesheet = stylesheet.sheet;
      stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
    }
  }

    /* 1 Update the theme with the AppSkinInfo retrieved from the host product. */
    /* 2 Update the theme with the AppSkinInfo retrieved from the host product. */
    /* 3 Update the theme with the AppSkinInfo retrieved from the host product. */
    /* 4 Update the theme with the AppSkinInfo retrieved from the host product. */
  function updateThemeWithAppSkinInfo(appSkinInfo) {
    var fontColor;
    var styleId = "hostStyle";
    var sentinelColor = appSkinInfo.panelBackgroundColor.color.red;
    var themeIsLight = sentinelColor > 128;

    if (sentinelColor > 200) { // exact: 240 (#D6D6D6)
      // this is where font color and other theme dependent stuff could go
      document.getElementById('theme').href = "css/superlight.css";
    } else if (sentinelColor > 180) { // exact: 184 (#B8B8B8)
     document.getElementById('theme').href = "css/light.css";
    } else if (sentinelColor > 80) { // exact: 83 (#535353)
      document.getElementById('theme').href = "css/dark.css";
    } else if (sentinelColor >= 50) { // exact: 52 (#343434)
      document.getElementById('theme').href = "superdark.css";
    }

    fontColor = (themeIsLight) ? "333" : "DDD";

    // Add your rules here in styles.css, which being
    // loaded after Topcoat, overrides these selectors
    insertRule(styleId, "body", "color:" + "#" + fontColor);
  }

  function onAppThemeColorChanged(event) {
    var appSkinInfo = csInterface.getHostEnvironment().appSkinInfo;
    updateThemeWithAppSkinInfo(appSkinInfo);
  }

  function init() {     
    var appSkinInfo = csInterface.getHostEnvironment().appSkinInfo;
    updateThemeWithAppSkinInfo(appSkinInfo);
    csInterface.addEventListener(CSInterface.THEME_COLOR_CHANGED_EVENT, onAppThemeColorChanged);
  }

  return {
    init: init
  };

}());