text: /*MIT License
  
  Copyright (c) 2021 Dylan Delaporte
  
  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.*/
  
  class Session {
      static instance;
  
      stage = new Konva.Stage({
          container: "container",
          width: VARS.currentWidth,
          height: VARS.currentHeight,
          offset: {
              x: -VARS.currentWidth / 2,
              y: -VARS.currentHeight / 2
          }
      });
  
      backgroundLayer = new Konva.Layer();
      layer = new Konva.Layer();
      toolLayer = new Konva.Layer();
  
      gameArea = new Konva.Circle({
          x: 0,
          y: 0,
          radius: VARS.gameWidth / 2,
          stroke: 'rgb(29,29,29)',
          strokeWidth: 6,
          shadowColor: 'black',
          shadowBlur: 10,
          shadowOpacity: 0.5,
          listening: false
      });
  
      gameInnerArea = new Konva.Circle({
          x: 0,
          y: 0,
          radius: (VARS.gameWidth - 8) / 2,
          fillRadialGradientStartPoint: { x: 0, y: 0 },
          fillRadialGradientStartRadius: 500,
          fillRadialGradientEndPoint: { x: 0, y: 0 },
          fillRadialGradientEndRadius: 0,
          fillRadialGradientColorStops: [0, 'rgb(14,78,109)', 1, 'rgb(18,100,140)'],
          stroke: 'rgb(102,102,102)',
          strokeWidth: 2,
          listening: false
      });
  
      gameTable = new Konva.Circle({
          x: 0,
          y: 0,
          radius: VARS.gameWidth / 2 * 0.35,
          fill: 'rgb(198,206,210)',
          stroke: 'rgb(12,12,12)',
          strokeWidth: 4,
          shadowColor: 'black',
          shadowBlur: 10,
          shadowOpacity: 0.5,
          listening: false
      });
  
      zoom = new Zoom()
      cardSelection = new CardSelection();
      contextMenu = new ContextMenu();
  
      constructor() {
      }
  
      static get() {
          if (!Session.instance) {
              Session.instance = new Session();
          }
  
          return Session.instance;
      }
  
      init() {
          window.onclick = () => {
              Tools.debug("Session -> event -> onclick");
              this.contextMenu.hide();
  
              return false;
          }
  
          let reload = false;
  
          window.onresize = () => {
              Tools.debug("Session -> event -> resize");
  
              if (!reload) {
                  reload = true;
                  setTimeout(() => location.reload())
              }
  
              return false;
          }
  
          const that = this;
  
          //this.stage.container().style.background = 'radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(112,110,131,1) 74%, rgba(2,0,36,1) 100%)';
  
          this.stage.on('wheel', (e) => {
              Tools.debug("Session -> event -> wheel");
              e.evt.preventDefault();
  
              that.zoom.zoom(e.evt.deltaY);
          });
  
          this.stage.on('mousedown touchstart', (e) => {
              Tools.debug("Session -> event -> mousedown touchstart");
  
              // do nothing if we mousedown on a card
              if (e.target._id !== that.stage._id
                  && e.target._id !== that.gameArea._id
                  && e.target._id !== that.gameTable._id) {
                  return;
              }
  
              that.cardSelection.start();
          });
  
          this.stage.on('mousemove touchmove', () => {
              console.log(that.getPointerPosition())
  
              Tools.debug("Session -> event -> mousemove touchmove");
              that.cardSelection.move();
          });
  
          this.stage.on('mouseup touchend', () => {
              Tools.debug("Session -> event -> mouseup touchend");
              that.cardSelection.stop();
          });
  
          this.stage.on('contextmenu', function (e) {
              Tools.debug("Session -> event -> contextmenu");
  
              // prevent default behavior
              e.evt.preventDefault();
  
              if (e.target._id === that.stage._id || Object.keys(VARS.selectedCards).length < 1) {
                  return;
              }
  
              that.contextMenu.show(e.target._id);
          });
  
          this.backgroundLayer.add(this.gameArea);
          this.backgroundLayer.add(this.gameInnerArea);
          this.backgroundLayer.add(this.gameTable)
  
          this.stage.add(this.backgroundLayer)
          this.stage.add(this.layer);
  
          this.toolLayer.add(this.cardSelection.selectionRectangle);
  
          this.stage.add(this.toolLayer);
  
          this.zoom.autoScale();
      }
  
      getLayer() {
          return this.layer;
      }
  
      addToLayer(element) {
          this.layer.add(element);
      }
  
      draw(batch) {
          Tools.debug("Session -> method -> draw: batch=" + batch);
  
          if (batch)
              this.layer.batchDraw();
          else
              this.layer.draw();
      }
  
      getStage() {
          return this.stage;
      }
  
      getPointerPosition() {
          return this.stage.getPointerPosition();
      }
  }
  
  class Zoom {
      scaleBy = 1.01;
  
      constructor() {
      }
  
      zoom(deltaY) {
          const oldScale = Session.get().getStage().scaleX();
          this.applyScale(deltaY > 0 ? oldScale * this.scaleBy : oldScale / this.scaleBy, Session.get().getPointerPosition());
      }
  
      autoScale() {
          const widthRatio = VARS.currentWidth / VARS.gameWidth;
          const heightRatio = VARS.currentHeight / VARS.gameHeight;
  
          if (widthRatio < heightRatio) {
              Tools.debug("Zoom -> method -> autoScale: widthRatio=" + widthRatio);
              this.applyScale(widthRatio, {x: VARS.currentWidth / 2, y: VARS.currentHeight / 2});
          } else {
              Tools.debug("Zoom -> method -> autoScale: heightRatio=" + heightRatio);
              this.applyScale(heightRatio, {x: VARS.currentWidth / 2, y: VARS.currentHeight / 2});
          }
      }
  
      applyScale(newScale, pointer) {
          console.log(pointer);
  
          const oldScale = Session.get().getStage().scaleX();
  
          const mousePointTo = {
              x: (pointer.x - Session.get().getStage().x()) / oldScale,
              y: (pointer.y - Session.get().getStage().y()) / oldScale,
          };
  
          Session.get().getStage().scale({x: newScale, y: newScale});
  
          Session.get().getStage().position({
              x: pointer.x - mousePointTo.x * newScale,
              y: pointer.y - mousePointTo.y * newScale,
          });
  
          Session.get().backgroundLayer.batchDraw();
          Session.get().layer.batchDraw();
      }
  }
  
  class CardSelection {
      selectionRectangle = new Konva.Rect({
          fill: 'rgba(0,0,255,0.5)',
          visible: false
      });
  
      x1 = null;
      y1 = null;
      x2 = null;
      y2 = null;
  
      constructor() {
      }
  
      start() {
          Tools.debug("CardSelection -> start");
  
          const pointerPosition = Session.get().getPointerPosition();
  
          this.x1 = ((pointerPosition.x - Session.get().getStage().x()) / Session.get().getStage().scaleX()) - (VARS.currentWidth / 2);
          this.y1 = ((pointerPosition.y - Session.get().getStage().y()) / Session.get().getStage().scaleY()) - (VARS.currentHeight / 2);
          this.x2 = this.x1;
          this.y2 = this.y1;
  
          this.selectionRectangle.visible(true);
          this.selectionRectangle.width(0);
          this.selectionRectangle.height(0);
      }
  
      move() {
          Tools.debug("CardSelection -> move");
  
          // no nothing if we didn't start selection
          if (!this.selectionRectangle.visible()) {
              return;
          }
  
          Tools.debug("CardSelection -> yes");
  
          const pointerPosition = Session.get().getPointerPosition();
  
          this.x2 = ((pointerPosition.x - Session.get().getStage().x()) / Session.get().getStage().scaleX()) - (VARS.currentWidth / 2);
          this.y2 = ((pointerPosition.y - Session.get().getStage().y()) / Session.get().getStage().scaleY()) - (VARS.currentHeight / 2);
  
          this.selectionRectangle.setAttrs({
              x: Math.min(this.x1, this.x2),
              y: Math.min(this.y1, this.y2),
              width: Math.abs(this.x2 - this.x1),
              height: Math.abs(this.y2 - this.y1),
          });
  
          Session.get().toolLayer.batchDraw();
      }
  
      stop() {
          Tools.debug("CardSelection -> method -> Stop");
  
          const that = this;
  
          // no nothing if we didn't start selection
          setTimeout(() => {
              that.selectionRectangle.visible(false);
              Session.get().toolLayer.batchDraw();
          });
  
          if (this.x1 === undefined) {
              return;
          }
  
          if (Math.abs(this.x1 - this.x2) < 10) {
              Tools.debug("CardSelection -> method -> stop -> clear")
  
              const temporarySelectedCards = VARS.selectedCards;
              VARS.selectedCards = {};
  
              for (const card in temporarySelectedCards) {
                  temporarySelectedCards[card].setVisible(temporarySelectedCards[card].data.visible);
              }
          } else {
              Tools.debug("CardSelection -> method -> stop -> apply")
  
              const box = this.selectionRectangle.getClientRect();
              const selected = Session.get().getLayer().getChildren().filter((shape) =>
                  Konva.Util.haveIntersection(box, shape.getClientRect())
              );
  
              for (const group of selected) {
                  for (const card in VARS.cards) {
                      if (VARS.cards[card].object.group._id === group._id) {
                          VARS.cards[card].object.box.stroke("blue");
                          VARS.selectedCards[card] = VARS.cards[card];
                      }
                  }
              }
          }
  
          Session.get().draw(true);
      }
  }
  
  class ContextMenu {
      contextMenu = document.getElementById("context-menu");
      contextMenuCardId = null;
  
      constructor() {
          const that = this;
  
          document.getElementById("pile-button").onclick = () => {
              if (Object.keys(VARS.selectedCards).length > 0 && that.contextMenuCardId !== null) {
                  let events = [];
  
                  for (const card in VARS.selectedCards) {
                      if (card !== that.contextMenuCardId) {
                          VARS.selectedCards[card].object.group.to({
                              x: VARS.selectedCards[that.contextMenuCardId].object.group.x(),
                              y: VARS.selectedCards[that.contextMenuCardId].object.group.y(),
                              duration: 1
                          });
  
                          events.push({
                              id: card,
                              x: VARS.selectedCards[that.contextMenuCardId].object.group.x() / (VARS.currentWidth / 2),
                              y: VARS.selectedCards[that.contextMenuCardId].object.group.y() / (VARS.currentHeight / 2)
                          });
                      }
                  }
  
                  Session.get().draw(false)
  
                  Connection.get().sendEvent({multiple: events});
              }
  
              return false;
          };
  
          document.getElementById("random-order-button").onclick = () => {
              const cardsKey = Object.keys(selectedCards);
  
              if (cardsKey.length > 0 && contextMenuCardId !== null) {
                  const cardsShuffleKey = shuffle(Object.keys(selectedCards));
                  let events = [];
  
                  for (let i = 0; i < cardsKey.length; i++) {
                      events.push({
                          id: cardsKey[i],
                          index: selectedCards[cardsShuffleKey[i]].data.index
                      });
                  }
  
                  sendEvent({multiple: events});
              }
          }
  
          function setVisibilityToSelectedCards(visible = "none") {
              if (Object.keys(VARS.selectedCards).length > 0 && that.contextMenuCardId !== null) {
                  let events = [];
  
                  for (const card in VARS.selectedCards) {
                      events.push({
                          id: card,
                          visible: visible
                      });
                  }
  
                  Connection.get().sendEvent({multiple: events});
              }
          }
  
          document.getElementById("hide-button").onclick = () => {
              setVisibilityToSelectedCards();
              return false;
          };
  
          document.getElementById("show-button").onclick = () => {
              setVisibilityToSelectedCards(username);
              return false;
          };
  
          document.getElementById("show-to-all-button").onclick = () => {
              setVisibilityToSelectedCards("all");
              return false;
          };
      }
  
      show(targetId) {
          console.log("ContextMenu -> show")
  
          this.contextMenuCardId = null;
  
          for (const [key, value] of Object.entries(VARS.selectedCards)) {
              if (value.object.box._id === targetId) {
                  this.contextMenuCardId = key;
                  break;
              }
          }
  
          this.contextMenu.style.display = 'initial';
  
          const containerRect = Session.get().getStage().container().getBoundingClientRect();
          const pointerPosition = Session.get().getPointerPosition()
  
          this.contextMenu.style.top = containerRect.top + pointerPosition.y + 4 + 'px';
          this.contextMenu.style.left = containerRect.left + pointerPosition.x + 4 + 'px';
      }
  
      hide() {
          this.contextMenu.style.display = 'none';
      }
  }
  