include("class.lua")

Vector2d = class()

function Vector2d:init(x, y)
	self.x = x
	self.y = y
end

function Vector2d:__add(vec2d)
	if (self:__checkVar(vec2d)) then
		return self
	end
	
	return Vector2d(vec2d.x + self.x, vec2d.y + self.y)
end

function Vector2d:__sub(vec2d)
	if (self:__checkVar(vec2d)) then
		return self
	end
	
	return Vector2d(vec2d.x - self.x, vec2d.y - self.y)
end

function Vector2d:__mul(vec2d)
	if (vec2d == nil) then
		return 0
	end
	if (type(vec2d) == "number") then
		return Vector2d(self.x * vec2d, self.y * vec2d)
	end
	
	if (not self:__checkVar(vec2d)) then
		return self
	end
	
	return vec2d.x * self.x + vec2d.y * self.y
end

function Vector2d:__len()
	return self:getLength()
end

function Vector2d:getLength()
	return math.sqrt(self.x^2 + self.y^2)
end

function Vector2d:__eq(vec2d)
	if (not self:__checkVar(vec2d)) then
		return false
	end
	
	return self.x == vec2d.x and self.y == vec2d.y
end

function Vector2d:__checkVar(var)
	if (var == nil) then
		return false
	end
	
	if (not type(var) == "table") then
		return false
	end
	
	if (not type(var.is_a) == "function") then
		return false
	end
	
	if (not var:is_a(Vector2d)) then
		return false
	end
	
	return true
end

function Vector2d:__tostring()
	return string.format("(%d, %d)", self.x, self.y)
end

function Vector2d:dotProduct(vec2d)
	return self * vec2d
end

function Vector2d:setFromVec(vec2d)
	if (not self:__checkVar(vec2d)) then
		return false
	end
	
	self.x = vec2d.x
	self.y = vec2d.y
	
	return true
end

function Vector2d:set(x, y)
	if (type(x) == "nubmer" and type(y) == "number") then
		self.x = x
		self.y = y
		return true
	else
		return false
	end
end

function Vector2d:normalize()
	local temp = Vector2d()
	local len = 1 / self:getLength()

	temp.x = self.x * len
	temp.y = self.y * len
	
	return temp
end

function Vector2d:normalizeLocal()
	self:setFromVec(self:normalize())
	
	return self
end