System.register(['reactive-jsx', 'src/components/widgets/lively-morph.js', 'src/client/fileindex.js', 'src/client/graphics.js'], function (_export, _context) {
  "use strict";

  var _childSpread, _childElement, _attributeExpression, _attributeStringLiteral, _childExpression, _children, _attributes, _element, Morph, FileIndex, pt;

  return {
    setters: [function (_reactiveJsx) {
      _childSpread = _reactiveJsx.childSpread;
      _childElement = _reactiveJsx.childElement;
      _attributeExpression = _reactiveJsx.attributeExpression;
      _attributeStringLiteral = _reactiveJsx.attributeStringLiteral;
      _childExpression = _reactiveJsx.childExpression;
      _children = _reactiveJsx.children;
      _attributes = _reactiveJsx.attributes;
      _element = _reactiveJsx.element;
    }, function (_srcComponentsWidgetsLivelyMorphJs) {
      Morph = _srcComponentsWidgetsLivelyMorphJs.default;
    }, function (_srcClientFileindexJs) {
      FileIndex = _srcClientFileindexJs.default;
    }, function (_srcClientGraphicsJs) {
      pt = _srcClientGraphicsJs.pt;
    }],
    execute: function () {
      const __SystemJSRewritingHack = {};
      _recorder_._src_components_tools_lively_generic_search_js = _recorder_._src_components_tools_lively_generic_search_js || {};
      Object.defineProperty(_recorder_._src_components_tools_lively_generic_search_js, 'Morph', {
        get() {
          return Morph;
        },

        set(thisIsVererySecretVariableName) {
          Morph = thisIsVererySecretVariableName;
          return true;
        },

        enumerable: true,
        configurable: true
      });
      Object.defineProperty(_recorder_._src_components_tools_lively_generic_search_js, 'FileIndex', {
        get() {
          return FileIndex;
        },

        set(thisIsVererySecretVariableName) {
          FileIndex = thisIsVererySecretVariableName;
          return true;
        },

        enumerable: true,
        configurable: true
      });
      Object.defineProperty(_recorder_._src_components_tools_lively_generic_search_js, 'pt', {
        get() {
          return pt;
        },

        set(thisIsVererySecretVariableName) {
          pt = thisIsVererySecretVariableName;
          return true;
        },

        enumerable: true,
        configurable: true
      });
      class LivelyGenericSearch extends Morph {
        get input() {
          return this.get('#input');
        }
        get outer() {
          return this.get('#outer');
        }
        get inner() {
          return this.get('#inner');
        }
        get list() {
          return this.get('#list');
        }

        // #TODO: mark as meta
        async initialize() {
          this.windowTitle = "LivelyGenericSearch";

          this.startSearching = (() => this.calculateListToShow()).throttle(300);
          this.setupInput();

          lively.html.registerKeys(this); // automatically installs handler for some methods

          this.addEventListener("focusout", () => this.close());
          this.addEventListener("click", evt => this.onClick(evt));
          this.init();
        }

        setupInput() {
          this.input.addEventListener("keyup", evt => {
            this.onKeyInput(evt);
          });
          this.input.addEventListener('input', evt => this.inputChanged(evt));
        }

        inputChanged(evt) {
          // lively.success('input is now ${this.input.value}', evt)
          this.startSearching();
        }

        close() {
          try {
            this.remove();
          } catch (e) {
            // no errors please..
          }
        }

        onKeyInput(evt) {
          const keyActions = new Map([[13, evt => {
            this.jumpToSelectedItem(evt);
            this.close();
          }], // ENTER
          [27, evt => this.close()]]);

          keyActions.getOrCreate(evt.keyCode, keyCode => evt => {})(evt);
        }

        onUpDown(evt) {
          evt.stopPropagation();
          evt.preventDefault();

          const currentItem = this.get('.selected');
          if (!currentItem) {
            return;
          }

          const nextItem = currentItem.previousElementSibling || this.getAllSubmorphs('.item').last;
          if (!nextItem) {
            return;
          }

          currentItem.classList.remove('selected');
          nextItem.classList.add('selected');
        }
        onDownDown(evt) {
          evt.stopPropagation();
          evt.preventDefault();

          const currentItem = this.get('.selected');
          if (!currentItem) {
            return;
          }

          var nextItem = currentItem.nextElementSibling || this.getAllSubmorphs('.item').first;
          if (!nextItem) {
            return;
          }

          currentItem.classList.remove('selected');
          nextItem.classList.add('selected');
        }

        async jumpToSelectedItem(evt) {
          this.jumpToItem(this.get('.selected'), evt);
        }

        async jumpToItem(item, evt) {
          if (!item) return;
          lively.openBrowser(item.getAttribute('file'), !evt.shiftKey);
          this.close();
        }

        onClick(evt) {
          var item = evt.composedPath().find(ea => ea.classList.contains("item"));
          this.jumpToItem(item, evt);
        }

        setFocus() {
          this.input.focus();
        }
        init() {
          lively.setPosition(this, pt(500, 100), 'fixed');
          this.files = this.getFiles();
          this.startSearching();
        }

        async getFiles() {
          var result = [];
          await FileIndex.current().db.files.each(file => result.push(file));
          return result;
        }

        async calculateListToShow() {
          var pattern = this.input.value;
          var search = new RegExp(pattern, 'ig');

          const filteredFiles = (await this.files).filter(file => {
            if (file.url.startsWith(lively4url)) {
              const relativePath = file.url.replace(/.*\//ig, '');
              return relativePath.match(search);
            } else {
              return false;
            }
          });

          const cutFiles = filteredFiles.slice(0, 50);
          this.updateList(cutFiles);
        }
        async updateList(filesToDisplay) {
          this.list.innerHTML = '';
          filesToDisplay = filesToDisplay.slice(0, 50);

          filesToDisplay.forEach(file => {
            const name = file.url.replace(lively4url, '');

            if (this.input.value.length >= 3) {
              var regex = new RegExp(this.input.value, 'ig');
              var text = name;
              const realResult = [];
              var result;
              var realStart = 0;
              var counter = 0;
              while ((result = regex.exec(text)) !== null) {
                var start = result.index;
                var l = result[0].length;

                var normal = _element('span', _attributes(), _children(_childExpression(text.substring(realStart, start))), {
                  file: 'https://lively-kernel.org/lively4/lively4-function-completion/src/components/tools/lively-generic-search.js',
                  end: {
                    column: 70,
                    line: 149
                  },
                  start: {
                    column: 23,
                    line: 149
                  }
                });
                var highlight = _element('span', _attributes(_attributeStringLiteral('style', 'color: red')), _children(_childExpression(result[0])), {
                  file: 'https://lively-kernel.org/lively4/lively4-function-completion/src/components/tools/lively-generic-search.js',
                  end: {
                    column: 69,
                    line: 150
                  },
                  start: {
                    column: 26,
                    line: 150
                  }
                });
                realResult.push(normal);
                realResult.push(highlight);
                realStart = start + l;
                if (counter++ > 10) {
                  break;
                }
              }
              realResult.push(_element('span', _attributes(), _children(_childExpression(text.substring(realStart, text.length))), {
                file: 'https://lively-kernel.org/lively4/lively4-function-completion/src/components/tools/lively-generic-search.js',
                end: {
                  column: 77,
                  line: 156
                },
                start: {
                  column: 24,
                  line: 156
                }
              }));

              this.list.appendChild(_element('div', _attributes(_attributeStringLiteral('class', 'item'), _attributeExpression('file', file.url)), _children(_childElement(_element('span', _attributes(), _children(_childSpread(realResult)), {
                file: 'https://lively-kernel.org/lively4/lively4-function-completion/src/components/tools/lively-generic-search.js',
                end: {
                  column: 92,
                  line: 159
                },
                start: {
                  column: 64,
                  line: 159
                }
              }))), {
                file: 'https://lively-kernel.org/lively4/lively4-function-completion/src/components/tools/lively-generic-search.js',
                end: {
                  column: 98,
                  line: 159
                },
                start: {
                  column: 30,
                  line: 159
                }
              }));
            } else {
              this.list.appendChild(_element('div', _attributes(_attributeStringLiteral('class', 'item'), _attributeExpression('file', file.url)), _children(_childElement(_element('span', _attributes(), _children(_childExpression(name)), {
                file: 'https://lively-kernel.org/lively4/lively4-function-completion/src/components/tools/lively-generic-search.js',
                end: {
                  column: 83,
                  line: 161
                },
                start: {
                  column: 64,
                  line: 161
                }
              }))), {
                file: 'https://lively-kernel.org/lively4/lively4-function-completion/src/components/tools/lively-generic-search.js',
                end: {
                  column: 89,
                  line: 161
                },
                start: {
                  column: 30,
                  line: 161
                }
              }));
            }
          });
          const first = this.list.querySelector('.item');
          if (first) {
            first.classList.add('selected');
          }
        }

        // this method is autmatically registered through the ``registerKeys`` method
        onKeyDown(evt) {
          // lively.notify("Key Down: " + evt.charCode)
        }

        livelyPreMigrate() {
          // is called on the old object before the migration
        }

        livelyMigrate(other) {
          // whenever a component is replaced with a newer version during development
          // this method is called on the new object during migration, but before initialization
          this.input.value = other.input.value;
          this.input.focus();
        }

        livelyInspect(contentNode, inspector) {
          // do nothing
        }
      }

      _export('default', LivelyGenericSearch);

      Object.defineProperty(_recorder_._src_components_tools_lively_generic_search_js, 'LivelyGenericSearch', {
        get() {
          return LivelyGenericSearch;
        },

        set(thisIsVererySecretVariableName) {
          _export('default', LivelyGenericSearch = thisIsVererySecretVariableName);

          return true;
        },

        enumerable: true,
        configurable: true
      });
    }
  };
});