System.register(["src/client/poid.js", "src/external/focalStorage.js", "utils"], function (_export, _context) {
  "use strict";

  var Scheme, PolymorphicIdentifier, focalStorage, parseQuery, getDeepProperty, lastTokenPromted, todoistData;
  return {
    setters: [function (_srcClientPoidJs) {
      Scheme = _srcClientPoidJs.Scheme;
      PolymorphicIdentifier = _srcClientPoidJs.default;
    }, function (_srcExternalFocalStorageJs) {
      focalStorage = _srcExternalFocalStorageJs.default;
    }, function (_utils) {
      parseQuery = _utils.parseQuery;
      getDeepProperty = _utils.getDeepProperty;
    }],
    execute: function () {
      _recorder_._src_client_protocols_todoist_js = _recorder_._src_client_protocols_todoist_js || {};
      _recorder_._src_client_protocols_todoist_js.Scheme = Scheme;
      _recorder_._src_client_protocols_todoist_js.PolymorphicIdentifier = PolymorphicIdentifier;
      _recorder_._src_client_protocols_todoist_js.focalStorage = focalStorage;
      _recorder_._src_client_protocols_todoist_js.getDeepProperty = getDeepProperty;
      _recorder_._src_client_protocols_todoist_js.parseQuery = parseQuery;
      lastTokenPromted = _recorder_._src_client_protocols_todoist_js.lastTokenPromted;
      _recorder_._src_client_protocols_todoist_js.lastTokenPromted = lastTokenPromted;
      todoistData = _recorder_._src_client_protocols_todoist_js.todoistData;
      _recorder_._src_client_protocols_todoist_js.todoistData = todoistData;


      /*MD
      
      [API documentation](https://developer.todoist.com/sync/v8)
      
      MD*/

      class TodoistScheme extends _recorder_._src_client_protocols_todoist_js.Scheme {

        get scheme() {
          return "todoist";
        }

        async todoistToken() {
          var token = await _recorder_._src_client_protocols_todoist_js.focalStorage.getItem("todoist-token");
          if (!token && (!_recorder_._src_client_protocols_todoist_js.lastTokenPromted || Date.now() - _recorder_._src_client_protocols_todoist_js.lastTokenPromted > 1000 * 5)) {
            // don't ask again for 5 seconds...
            _recorder_._src_client_protocols_todoist_js.lastTokenPromted = Date.now();
            token = await lively.prompt("todoist token required: ");
            if (token) {
              _recorder_._src_client_protocols_todoist_js.focalStorage.setItem("todoist-token", token);
            }
          }
          return token;
        }

        resolve() {
          return true;
        }

        async fetchData() {
          return await fetch(`https://todoist.com/api/v7/sync` + `?token=${await this.todoistToken()}` + `&sync_token=*` + `&resource_types=${encodeURI(JSON.stringify(["all"]))}`, {
            method: 'POST'
          }).then(r => r.json());
        }

        async getData() {
          if (!_recorder_._src_client_protocols_todoist_js.todoistData) _recorder_._src_client_protocols_todoist_js.todoistData = await this.fetchData();
          return _recorder_._src_client_protocols_todoist_js.todoistData;
        }

        async renderHTML(result) {
          return "<pre>" + JSON.stringify(result, undefined, 2) + "</pre>";
        }

        async GET(options) {
          let data = await this.getData();
          let urlObj = new URL(this.url);
          let m = urlObj.pathname.match(/^\/*([^/]+)\/?([^/]+)?$/);
          let type = m && m[1];
          let id = m && m[2];
          let result;
          if (!type) {
            result = data;
          } else {
            let list = data[type];
            if (!id) {
              result = list;
            } else {
              let item = list.find(ea => ea.id == id);
              result = item;
            }
          }
          if (urlObj.search == "?html") {
            return new Response((await this.renderHTML(result)), { status: 200 });
          }
          return new Response(JSON.stringify(result, undefined, 2), { status: 200 });
        }

        itemToFile(type, item) {
          return {
            name: "" + item.id,
            title: item.name || (item.content ? ("" + item.content).slice(0, 30) : undefined),
            parent: this.scheme + "://" + type + "/",
            type: "file"
          };
        }

        async OPTIONS() {
          let data = await this.getData();
          let urlObj = new URL(this.url);
          let m = urlObj.pathname.match(/^\/*([^/]+)\/?([^/]+)?$/);
          let type = m && m[1];
          let id = m && m[2];
          lively.notify("path" + urlObj.pathname + "type: " + type + " id:" + id);
          let result;
          if (!type) {
            result = {
              name: "root",
              type: "directory",
              parent: this.scheme + "://",
              contents: Object.keys(data).map(ea => ({
                name: ea,
                type: data[ea].map ? "directory" : "file"
              }))
            };
          } else {
            let list = data[type];
            if (!id) {
              result = {
                name: type,
                type: list.map ? "directory" : "file",
                parent: this.scheme + "://",
                contents: list.map ? list.map(ea => this.itemToFile(type, ea)) : undefined
              };
            } else {
              let item = list.find(ea => ea.id == id);
              result = this.itemToFile(type, item);
            }
          }
          return new Response(JSON.stringify(result), { status: 200 });
        }
      }

      _export("TodoistScheme", TodoistScheme);

      _recorder_._src_client_protocols_todoist_js.TodoistScheme = TodoistScheme;
      _recorder_._src_client_protocols_todoist_js.PolymorphicIdentifier.register(_recorder_._src_client_protocols_todoist_js.TodoistScheme);
    }
  };
});