<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jIO Dashboard</title>
</head>
<body>
  <table border="1" style="width: 100%;">
    <tr>
      <th style="text-align: center;" id="script_injection_space">
      </th>
    </tr>
    <tr style="font-style:italic;">
      <th>Storage Description</th>
    </tr>
    <tr>
      <th style="width:100%;">
        <textarea id="storagedescription" rows="10"
                  style="width:98%;"></textarea>
      </th>
    </tr>
    <tr>
      <td style="text-align: center;">
        <button onclick="fillMemoryDescription()">Memory</button>
        <button onclick="fillLocalDescription()">Local</button>
        <button onclick="fillDavDescription()">WebDAV</button>
        <button onclick="fillDavBasicDescription()">WebDAV Basic</button>
        <button onclick="fillERP5Description()">ERP5</button>
        <button onclick="fillCustomDescription()">Custom</button>
        <br /><button onclick="fillLastDescription()">Last</button>
        <button onclick="loadDescription()">Load</button>
        <button onclick="saveDescription()">Save</button>
      </td>
    </tr>
    <tr>
      <th><button onclick="createJIO()">Create JIO</button></th>
    </tr>
  </table>
  <br />
  <table border="1" style="width: 100%;">
    <tr>
      <td colspan="1" style="width: 50%;">
        <label for="metadata">Metadata or Parameters:</label>
        <textarea id="metadata" rows="3" style="width: 98%;">{}</textarea>
      </td>
      <td colspan="1" style="text-align: center;">
        Options:<br />
        <textarea id="options" rows="3" style="width: 98%;">{}</textarea>
      </td>
    </tr>
    <tr>
      <td colspan="2" style="text-align: center;">
        <button onclick="post()">post</button>
        <button onclick="put()">put</button>
        <button onclick="get()">get</button>
        <button onclick="window.remove()">remove</button>
        - <button onclick="putAttachment()">putAttachment</button>
        <button onclick="getAttachment()">getAttachment</button>
        <button onclick="removeAttachment()">removeAttachment</button>
        - <button onclick="allDocs()">allDocs</button>
        - <button onclick="check()">check</button>
        <button onclick="repair()">repair</button>
      </td>
    </tr>
    <tr>
      <td colspan="2" style="text-align: center;">
        <label for="times">Times</label>
        <input id="times" type="text" value="1" />
        <input id="times-lock" type="checkbox" checked="1" />
        <label for="times-lock">lock</label>
      </td>
    </tr>
  </table>
  <br />
  <div style="text-align: center;">
    Useful functions:
    <button onclick="scriptLogLocalStorage()">log localStorage</button>
    <button onclick="localStorage.clear()">clear localStorage</button>
    <button onclick="scriptRemoveAllDocs()">removeAllDocs</button>
    <button onclick="scriptRepairAllDocs()">repairAllDocs</button>
  </div>
  <hr />
  <button onclick="clearlog()">Clear Log</button>
  <hr />
  <div id="log">
  </div>
  <script type="text/javascript">
    <!--
var log_color = "white";

function select(string) {
  return document.querySelector(string);
}
function logGetColor() {
  if (log_color === "white") {
    log_color = "cyan";
  } else {
    log_color = "white";
  }
  return log_color;
}
function log(o) {
  var node = document.createElement("pre");
  node.setAttribute(
    "style",
    "background-color:" + logGetColor() +
      ";margin:0;padding:0;"
  );
  if (typeof o === "string") {
    node.textContent = o;
  } else {
    node.textContent = JSON.stringify(o, null, "  ");
  }
  select("#log").appendChild(node);
}
function error(o) {
  var node = document.createElement("pre");
  node.setAttribute(
    "style",
    "background-color:" + logGetColor() +
      ";margin:0;padding:0;"
  );
  if (typeof o === "string") {
    node.textContent = o;
  } else {
    node.textContent = JSON.stringify(o);
  }
  select("#log").appendChild(node);
}
function clearlog() {
  select("#log").innerHTML = "";
}

function injectScript(url) {
  var script = document.createElement("script");
  script.setAttribute("src", url);
  document.body.appendChild(script);
}
function injectLastScripts() {
  var i, scripts = JSON.parse(localStorage.getItem("jio_dashboard_injected_scripts") || "{}");
  for (i in scripts) {
    if (i) {
      injectScript(i);
    }
  }
}
function saveScripts() {
  var scripts = {};
  [].forEach.call(document.querySelectorAll("#script_injection_space input[type=\"text\"]"), function (input) {
    return scripts[input.value] = true;
  });

  localStorage.setItem("jio_dashboard_injected_scripts", JSON.stringify(scripts));
  location.href = location.href;
}
function buildScriptFields() {
  var space, el, i, count = 0, scripts;
  function createInput(value) {
    var e = document.createElement("input");
    e.setAttribute("type", "text");
    e.setAttribute("style", "width: 98%;");
    if (value) { e.value = value; }
    count += 1;
    return e;
  }
  scripts = JSON.parse(localStorage.getItem("jio_dashboard_injected_scripts") || "{}");
  space = select("#script_injection_space");
  el = document.createElement("div");
  el.textContent = "Additional scripts:";
  space.appendChild(el);
  for (i in scripts) {
    if (i) {
      space.appendChild(createInput(i));
    }
  }
  space.appendChild(createInput());
  el = document.createElement("input");
  el.setAttribute("type", "button");
  el.value = "Save scripts and refresh page";
  el.onclick = saveScripts;
  space.appendChild(el);
}
// clear log on Alt+L
document.addEventListener("keypress", function (event) {
  if (event.altKey === true && event.charCode === 108) {
    clearlog();
  }
});
        //-->
  </script>
  <script src="../lib/rsvp/rsvp-custom.js"></script>
  <script src="../src/sha256.amd.js"></script>
  <script src="../jio.js"></script>
  <script src="../src/jio.storage/localstorage.js"></script>
  <script src="../src/jio.storage/davstorage.js"></script>
  <script src="http://git.erp5.org/gitweb/uritemplate-js.git/blob_plain/HEAD:/bin/uritemplate-min.js"></script>
  <script src="../lib/uri/URI.js"></script>
  <script src="../src/jio.storage/erp5storage.js"></script>
  <script type="text/javascript">
    <!--

var my_jio = null;

injectLastScripts();
buildScriptFields();

function fillMemoryDescription() {
  select("#storagedescription").value = JSON.stringify({
    "type": "local",
    "username": "<username>",
    "application_name": "<app_name>",
    "mode": "memory"
  }, null, "  ")
}
function fillLocalDescription() {
  select("#storagedescription").value = JSON.stringify({
    "type": "local",
    "username": "<username>",
    "application_name": "<app_name>"
  }, null, "  ")
}
function fillDavDescription() {
  select("#storagedescription").value = JSON.stringify({
    "type": "dav",
    "url": "<url>"
  }, null, "  ")
}
function fillDavBasicDescription() {
  select("#storagedescription").value = JSON.stringify({
    "type": "dav",
    "url": "<url>",
    "basic_login": "<btoa(username + ':' + password)>"
  }, null, "  ")
}
function fillERP5Description() {
  select("#storagedescription").value = JSON.stringify({
    "type": "erp5",
    "url": "<url to hateoas web site>"
  }, null, "  ")
}
function fillCustomDescription() {
  select("#storagedescription").value = JSON.stringify({
    "type": "<type>"
  }, null, "  ")
}
function fillLastDescription() {
  select("#storagedescription").value =
    localStorage.getItem("last_jio_description") || "{}";
}
function saveDescription() {
  localStorage.setItem(
    "saved_jio_description",
    select("#storagedescription").value
  );
}
function loadDescription() {
  select("#storagedescription").value =
    localStorage.getItem("saved_jio_description") || "{}";
}
fillLastDescription();

function createJIO() {
  var description;
  try {
    description = JSON.parse(select("#storagedescription").value);
    my_jio = jIO.createJIO(description);
    description = JSON.stringify(description, null, "  ");
    log("JIO created\n" + description);
    localStorage.setItem("last_jio_description", description);
  } catch (e) {
    error("Storage description is not JSON parsable");
  }
}

function logError(begin_date, err) {
  log('time : ' + (Date.now() - begin_date));
  error('return :' + JSON.stringify(err, null, "  "));
  throw err;
}

function logAnswer(begin_date, val) {
  log('time : ' + (Date.now() - begin_date));
  log('return : ' + JSON.stringify(val, null, "  "));
  return val;
}

function command(method, num) {
  var begin_date = Date.now(), doc = {}, opts = {};

  if (!my_jio) {
    error('no jio set');
    return;
  }

  doc = select('#metadata').value;
  opts = select("#options").value;

  if (num !== undefined) {
    doc = doc.replace(/\\u0000/g, num);
    opts = opts.replace(/\\u0000/g, num);
  }

  doc = JSON.parse(doc);
  opts = JSON.parse(opts);

  log(method + '\ndoc: ' + JSON.stringify(doc, null, "  ") +
      '\nopts: ' + JSON.stringify(opts, null, "  "));

  if (method === "allDocs") {
    return my_jio.allDocs(opts).then(
      logAnswer.bind(null, begin_date),
      logError.bind(null, begin_date)
    );
  } else {
    return my_jio[method](doc, opts).then(
      logAnswer.bind(null, begin_date),
      logError.bind(null, begin_date)
    );
  }
}

function doCommandNTimes(method, i) {
  var n = 0, lock, promise_list = [];
  i = i > 0 ? i : 0;
  n = parseInt(select("#times").value, 10);
  lock = select("#times-lock").checked;
  if (!lock) {
    select("#times").value = "1";
  }
  if (!isFinite(n)) {
    n = 1;
  }
  return command(method, ++i).
    then(function (answer) {
      if (i < n) {
        return doCommandNTimes(method, i);
      }
      return answer;
    });
}

function post() {
  return doCommandNTimes("post");
}
function put() {
  return doCommandNTimes("put");
}
function get() {
  return doCommandNTimes("get");
}
function remove() {
  return doCommandNTimes("remove");
}
function putAttachment() {
  return doCommandNTimes("putAttachment");
}
function getAttachment() {
  return doCommandNTimes("getAttachment");
}
function removeAttachment() {
  return doCommandNTimes("removeAttachment");
}
function allDocs() {
  return doCommandNTimes("allDocs");
}
function check() {
  return doCommandNTimes("check");
}
function repair() {
  return doCommandNTimes("repair");
}

//////////////////////////////////////////////////////////////////////
// scripts

function scriptLogLocalStorage() {
  log("localStorage content\n" + JSON.stringify(localStorage, null, "  "));
}

function scriptRemoveAllDocs() {
  var original_metadata_value = select('#metadata').value;
  return command("allDocs").then(function (answer) {
    return jIO.util.forEach(answer.data.rows, function (row) {
      select("#metadata").value = JSON.stringify({"_id": row.id});
      var ret = command("remove");
      select('#metadata').value = original_metadata_value;
      return ret;
    });
  });
}

function scriptRepairAllDocs() {
  var original_metadata_value = select('#metadata').value;
  return command("allDocs").then(function (answer) {
    return jIO.util.forEach(answer.data.rows, function (row) {
      select("#metadata").value = JSON.stringify({"_id": row.id});
      var ret = command("repair");
      select("#metadata").value = original_metadata_value;
      return ret;
    });
  });
}
        //-->
  </script>
</body>
</html>