# Complete, except DetectError

from vector import *

class spring():
    def __init__(self, length, mass0, mass1):
        self.length = length
        self.k = 1000
        self.f = 2000
        self.mass0 = mass0 
        self.mass1 = mass1

    def exert_force(self):
        DISPLACEMENT = add(self.mass1.position, mult(self.mass0.position, -1)) # Position of m1 relative to m0, absolute direction
        REL_VELOCITY = add(self.mass1.velocity, mult(self.mass0.velocity, -1)) # Velocity of m1 relative to m0, absolute direction
        DOT_PRODUCT = dot_prod(DISPLACEMENT, REL_VELOCITY) # >0 stretched, <0 pressed
        
        ELASTIC = mult(DISPLACEMENT.unit(), self.k*(self.length - DISPLACEMENT.magnitude()))
        FRICTION = mult(DISPLACEMENT.unit(), -sign(DOT_PRODUCT))

        self.mass1.forces.append(ELASTIC)
        self.mass1.forces.append(FRICTION)
        self.mass0.forces.append(mult(ELASTIC, -1))
        self.mass0.forces.append(mult(FRICTION, -1))


    def detect_error(self):
        pass

def sign(x):
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0