var openDocs = 0;

function onLoaded() {
  var frame = document.getElementById("panel").contentWindow;
  bridge = new Bridge({ ui: new frame.GuideGuideHTMLUI() });
  frame.initGuideGuide(bridge);

  var csInterface = new CSInterface();
  updateThemeWithAppSkinInfo(csInterface.hostEnvironment.appSkinInfo);
  csInterface.addEventListener(CSInterface.THEME_COLOR_CHANGED_EVENT, onAppThemeColorChanged);
  csInterface.addEventListener('documentAfterActivate', updateSessionInfo);
  csInterface.addEventListener('documentAfterDeactivate', clearSessionInfo);

  persistent(true);
}

function updateSessionInfo(event){
  openDocs++;
  var frame = document.getElementById("panel").contentWindow;
  frame.GuideGuide.storeDocumentState();
}

function clearSessionInfo(event){
  openDocs--;
  var frame = document.getElementById("panel").contentWindow;
  if(openDocs === 0){ frame.GuideGuide.clearDocumentState(); }
}

function updateThemeWithAppSkinInfo(appSkinInfo) {
  var color = appSkinInfo.panelBackgroundColor.color;
  color = tinycolor("rgba(" + color.red + "," + color.green + "," + color.blue + "," + color.alpha + ")");
  var bg = color.toHex();
  var isLightTheme = color._r > 127;
  var magnatude = isLightTheme ? 0.5 : 0.4;
  var colors = {
    prefix: isLightTheme ? 'light' : 'dark',
    background: '#' + color.toHex(),
    button: '#' + tinycolor.darken(color.toHex(), 20*magnatude).toHex(),
    buttonHover: '#' + tinycolor.darken(color.toHex(), 50*magnatude).toHex(),
    buttonSelect: '#' + tinycolor.darken(color.toHex(), 80*magnatude).toHex(),
    text: isLightTheme ? '#333' : '#eee',
    highlight: isLightTheme ? '#608ef6' : '#789ff7',
    highlightHover: isLightTheme ? '#5a85e6' : '#608ef6',
    danger: '#c74040'
  };
  var frame = document.getElementById("panel").contentWindow;
  frame.GuideGuide.updateTheme(colors);
}

function onAppThemeColorChanged(event) {
  updateThemeWithAppSkinInfo(JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo);
}

function persistent(inOn) {
  var event;

  if (inOn) {
    event = new CSEvent("com.adobe.PhotoshopPersistent", "APPLICATION");
  } else {
    event = new CSEvent("com.adobe.PhotoshopUnPersistent", "APPLICATION");
  }

  event.extensionId = "com.cameronmcefee.guideguide.panel";
  var csInterface = new CSInterface();
  csInterface.dispatchEvent(event);
}
