/**
* Copyright (c) 2016 Aleksi 'Allexit' Talarmo
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Jash {

   export class SH implements JSTerminal.Program, TerminalInput.KeyListener, Std.Input, Std.Output {

      terminal: JSTerminal.Terminal;
      stdio: Std.IO;

      cursor: {x: number, y: number} = {x: 0, y: 0};
      scroll: number = 0;
      messages: JSTerminal.Character[][] = [];

      defaultStyle = "";
      currentPrintStyle = "";

      listenerId = 0;

      currentReadlines: Std.Readline[] = [];
      currentReadline = "";

      /**
      * Inherited from Program-interface. Not to be manually called.
      */
      create(terminal: JSTerminal.Terminal, stdio: Std.IO, args?: string[]) {
         this.terminal = terminal;
         this.stdio = stdio;
         this.stdio.setOutput(this);
         this.stdio.setInput(this);
         this.stdio.addListener(this);
      }

      /**
      * Inherited from Program-interface. Not to be manually called.
      */
      enable() {
         this.refresh();
         if (this.listenerId < 0) {
            this.stdio.addListener(this);
         }
      }

      /**
      * Inherited from Program-interface. Not to be manually called.
      */
      disable() {
         if (this.listenerId >= 0) {
            this.stdio.removeListener(this.listenerId);
            this.listenerId = -1;
         }
      }

      /**
      * Inherited from Program-interface. Not to be manually called.
      */
      onClose() {
         if (this.listenerId >= 0) {
            this.stdio.removeListener(this.listenerId);
            this.listenerId = -1;
         }
         return true;
      }

      /**
      * Inherited from TerminalInput.KeyListener-interface. Not to be manually called.
      */
      onListen(listenerId: number) {
         this.listenerId = listenerId;
      }

      /**
      * Inherited from TerminalInput.KeyListener-interface. Not to be manually called.
      */
      handleKeypress(keypress: JQueryKeyEventObject) {

      }

      /**
      * Inherited from TerminalInput.KeyListener-interface. Not to be manually called.
      */
      handleKeydown(keydown: JQueryKeyEventObject) {
         if (this.currentReadlines.length == 0) { return; }

         let key = keydown.key
         if (key.length == 1) {
            this.currentReadline += key;
            if (this.currentReadlines[0].onChangeCallback !== undefined) {
               this.currentReadlines[0].onChangeCallback(this.currentReadline);
            }
            if (key == "/") {
               keydown.preventDefault();
            }
         }
         else {
            switch (keydown.keyCode) {
               case (32): {
                  this.currentReadline += " ";
                  if (this.currentReadlines[0].onChangeCallback !== undefined) {
                     this.currentReadlines[0].onChangeCallback(this.currentReadline);
                  }
                  break;
               }
               case (8): {
                  this.currentReadline = this.currentReadline.substr(0, this.currentReadline.length - 1);
                  if (this.currentReadlines[0].onChangeCallback !== undefined) {
                     this.currentReadlines[0].onChangeCallback(this.currentReadline);
                  }
                  keydown.preventDefault();
                  break;
               }
               case (13): {
                  let currReadline = this.currentReadlines[0];
                  if (currReadline.printAfterDone) {
                     let text = currReadline.prefix + this.currentReadline;
                     this.print(text, currReadline.style);
                  }
                  this.currentReadlines.shift().callback(this.currentReadline);
                  this.currentReadline = "";
               }
               case (0): {
                  if (keydown.key == "Dead") {
                     this.currentReadline += "~";

                     if (this.currentReadlines[0].onChangeCallback !== undefined) {
                        this.currentReadlines[0].onChangeCallback(this.currentReadline);
                     }
                  }
               }
            }
         }
         this.refresh();
      }

      /**
      * Inherited from TerminalInput.KeyListener-interface. Not to be manually called.
      */
      handleKeyup(keyup: JQueryKeyEventObject) {

      }

      /**
      * Inherited from Std.Input-interface. Not to be manually called.
      */
      readline(readline: Std.Readline) {
         this.currentReadline = readline.default || "";
         this.currentReadlines.push(readline);
         this.refresh();
      }

      /**
      * Inherited from Std.Output-interface. Not to be manually called.
      */
      print(text: string, style?: string) {
         style = style || this.currentPrintStyle || this.defaultStyle;

         let isAtEnd = (this.messages.length - this.terminal.height - this.scroll) <= 0


         for (let i = 0; i < text.length; i++) {
            let char = text[i];
            if (char == "\n") {
               if (this.cursor.y != 0 || this.cursor.x != 0) {
                  this.moveCursorNewline();
               }
               continue;
            }
            this.putCharacter(new JSTerminal.Character(char, style));
         }
         if (this.messages.length > this.terminal.height) {
            this.scroll = this.messages.length - this.terminal.height;
         }
      }

      /**
      * Inherited from Std.Output-interface. Not to be manually called.
      */
      println(text: string, style?: string) {
         this.print("\n" + text, style || this.currentPrintStyle || this.defaultStyle);
      }

      /**
      * Inherited from Std.Output-interface. Not to be manually called.
      */
      clear(style?: string) {
         this.messages = [];
         this.scroll = 0;
      }

      /**
      * Inherited from Std.Output-interface. Not to be manually called.
      */
      refresh(alsoRenderTerminal: boolean = true) {
         this.terminal.clearScreen(this.defaultStyle);

         let toDraw: JSTerminal.Character[][] = [];

         let messages: JSTerminal.Character[][] = [];
         for (let i in this.messages) {
            messages.push(this.messages[i].slice());
         }
         if (this.currentReadlines.length > 0 && !this.currentReadlines[0].hidden) {
            let readline = this.currentReadlines[0];
            let readlinePart = (readline.prefix || "") + this.currentReadline;
            let tempCursorPos = {x: this.cursor.x, y: this.cursor.y};
            for (let i = 0; i < readlinePart.length; i++) {
               let char = readlinePart[i];
               if (char == "\n") {
                  this.moveCursorNewline();
                  continue;
               }
               this.putCharacterTo(
                  new JSTerminal.Character(char, (readline.style || this.defaultStyle)),
                  messages);

            }
            this.cursor = tempCursorPos;
         }


         let start = messages.length - 1;

         for (let i = this.scroll;
               i < messages.length && toDraw.length < this.terminal.height;
               i++) {
            if (i < 0 || messages[i].length == 0) { toDraw.push([]); continue; }
            let rows = Math.ceil(messages[i].length/this.terminal.width);
            for (let r = 0; r < rows; r++) {
               toDraw.push(
                  messages[i].slice(
                     r * this.terminal.width,
                     (r + 1) * this.terminal.width));
            }
         }
         toDraw = toDraw.slice(-this.terminal.height);

         toDraw.forEach((row, y) => {
            row.forEach((c, x) => {
               this.terminal.putTrueChar(c, x, y);
            });
         });

         if (!alsoRenderTerminal) { return; }
         this.terminal.render();
      }

      /**
      * Utility function for print. Prints out one character at cursor.
      */
      putCharacter(character: JSTerminal.Character) {
         this.putCharacterTo(character, this.messages);
      }

      private putCharacterTo(character: JSTerminal.Character, charArray: JSTerminal.Character[][]) {
         while (this.cursor.y >= charArray.length) {
            charArray.push([]);
         }
         if (this.cursor.x >= charArray[this.cursor.y].length) {
            charArray[this.cursor.y].push(character);
            this.moveCursor(1);
            return;
         }
         charArray[this.cursor.y][this.cursor.x] = character;
         this.moveCursor(1);
      }

      /**
      * Removes a character and moves the cursor backwards.
      */
      removeCharacter() {
         if (this.messages[this.cursor.y] == []) {
            let rowToRemove = this.cursor.y;
            this.moveCursor(-1);
            this.messages.splice(this.cursor.y, 1);
            return;
         }
         let toRemove = {x: this.cursor.x, y: this.cursor.y};
         this.moveCursor(-1);
         this.messages[toRemove.y].splice(toRemove.x - 1, 1);
      }

      /**
      * Set the default style to be used when printing and clearing the screen.
      */
      setDefaultStyle(style: string) {
         this.defaultStyle = style;
      }

      /**
      * Set the current 'default' style for printing.
      * This is only temporary and can be reversed with calling it with a null-parameter.
      */
      setStyle(style: string) {
         this.currentPrintStyle = style;
      }

      /**
      * Moves the cursor by 'amount' forwards or backwards.
      * Handles text wrapping.
      */
      moveCursor(amount: number) {
         this.cursor.x += amount;
         this.cursor.y += Math.floor((this.cursor.x)/(this.terminal.width));
         this.cursor.x = this.cursor.x % (this.terminal.width);
         if (this.cursor.x < 0) {
            this.cursor.x = this.messages[this.cursor.y].length - 1 - this.cursor.x;
         }
      }

      /*
      * Moves the cursor vertically by amount. Works weirdly if cursor.x not handled manually.
      */
      moveCursorVertically(amount: number) {
         this.cursor.y += amount;
      }

      /*
      * Moves the cursor down to the next line and sets the x to 0.
      */
      moveCursorNewline() {
         this.moveCursorVertically(1);
         this.cursor.x = 0;
      }

      /*
      * Does the opposite as moveCursorNewline
      */
      moveCursorPreviousLine() {
         this.moveCursorVertically(-1);
         this.cursor.x = this.terminal.width - 1;
      }
   }

}
