'use strict';

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.add = function (point) {
  return new Point(this.x + point.x, this.y + point.y);
};

Point.prototype.sub = function (point) {
  return new Point(this.x - point.x, this.y - point.y);
};

Point.prototype.mul = function (value) {
  return new Point(this.x * value, this.y * value);
};

Point.prototype.div = function (value) {
  return new Point(this.x / value, this.y / value);
};

Point.prototype.dist = function () {
  return Math.sqrt(this.x * this.x + this.y * this.y);
};

Point.prototype.sqr = function () {
  return this.x * this.x + this.y * this.y;
};

/*
 * Check if 3 points are in line, and second in the midle.
 * Used to replace quad curves with lines or join lines
 *
 */
function isInLine(p1, m, p2, accuracy) {
  var a = p1.sub(m).sqr();
  var b = p2.sub(m).sqr();
  var c = p1.sub(p2).sqr();

  // control point not between anchors
  if ((a > (b + c)) || (b > (a + c))) {
    return false;
  }

  // count distance via scalar multiplication
  var distance = Math.sqrt(Math.pow((p1.x - m.x) * (p2.y - m.y) - (p2.x - m.x) * (p1.y - m.y), 2) / c);

  return distance < accuracy ? true : false;
}

module.exports.Point = Point;
module.exports.isInLine = isInLine;
