/**
 * @author mrdoob / http://mrdoob.com/
 */

var Stats = function (canvasId) {
  var beginTime = Date.now(), prevTime = beginTime, frames = 0;
  //@ts-ignore
  var fpsPanel = new Stats.Panel(canvasId, 'FPS', '#0ff', '#002');

  return {
    begin: function () {
      beginTime = Date.now();
    },

    end: function () {
      frames++;
      var time = Date.now();

      if (time >= prevTime + 1000) {
        fpsPanel.update((frames * 1000) / (time - prevTime), 100.0);

        prevTime = time;
        frames = 0;
      }

      return time;
    },

    update: function () {
      beginTime = this.end();
    },
  };
};
//@ts-ignore
Stats.Panel = function (canvasId, name, fg, bg) {
  var min = Infinity, max = 0, round = Math.round;
  var PR = 3;

  var WIDTH = 80 * PR, HEIGHT = 48 * PR,
    TEXT_X = 3 * PR, TEXT_Y = 2 * PR,
    GRAPH_X = 3 * PR, GRAPH_Y = 15 * PR,
    GRAPH_WIDTH = 74 * PR, GRAPH_HEIGHT = 30 * PR;

  var GRAPH_SIZE = GRAPH_WIDTH / PR;

  var items = [];

  var context //= my.createCanvasContext(canvasId);
  //@ts-ignore
  my.createCanvas({
    id: canvasId,
    success: (ccc) => {
      context = ccc.getContext("2d")
      context.font = 'bold ' + (9 * PR) + 'px Helvetica,Arial,sans-serif';
      // context.setTextBaseline('top');
      context.textBaseline = 'top'
      drawWithoutGraph(name);
      // context.draw();
    }
  })


  return {
    update: function (value, maxValue) {
      items.push(value);
      while (items.length > GRAPH_SIZE) {
        items.shift();
      }

      min = Math.min(min, value);
      max = Math.max(max, value);

      drawWithoutGraph(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')');

      // graph inner
      for (var i = 0; i < items.length; i++) {
        var startPos = GRAPH_X + (i + GRAPH_SIZE - items.length) * PR;

        // context.setFillStyle(fg);
        // context.setGlobalAlpha(1);
        context.fillStyle = fg;
        context.globalAlpha = 1;
        context.fillRect(startPos, GRAPH_Y, PR, GRAPH_HEIGHT);

        // context.setFillStyle(bg);
        // context.setGlobalAlpha(0.9);
        context.fillStyle = bg;
        context.globalAlpha = 0.9;
        context.fillRect(startPos, GRAPH_Y, PR, round((1 - (items[i] / maxValue)) * GRAPH_HEIGHT));
      }

      // context.draw();
    }
  };

  function drawWithoutGraph(text) {
    // bg
    // context.setFillStyle(bg);
    // context.setGlobalAlpha(1);
    context.fillStyle = bg;
    context.globalAlpha = 1;
    context.fillRect(0, 0, WIDTH, HEIGHT);

    // text
    // context.setFillStyle(fg);
    context.fillStyle = fg;
    context.fillText(text, TEXT_X, TEXT_Y);

    // graph bg
    context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
    // context.setFillStyle(bg);
    // context.setGlobalAlpha(0.9);
    context.fillStyle = bg;
    context.globalAlpha = 0.9;
    context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  }
};

export { Stats /*as default*/ };
