################
# > Jimmy Pet: A cute holographic controllable pet.
# > How to use: Spawn it and use '!follow', '!stay' or '!fetch' to control Jimmy. Throw Jimmys ball and say '!fetch' for lots of fun.
################

@name My Pet Jimmy's Ball
@outputs BodyPos:vector BodyAng:angle OPos:vector Action:string
@outputs FetchBall Distance BallDistance
@persist O:entity
@model models/dav0r/hoverball.mdl

interval(10)

if (first() | duped()) {
    holoCreate(0)
    holoPos(0, entity():pos())
    holoColor(0, vec(0,255,0))
    Body = holoEntity(0)
    BodyPos = Body:pos()
    BodyAng = Body:angles()
    holoCreate(1)
    holoPos(1, BodyPos+vec(-3,0,8))
    holoScale(1, vec(0.2,0.2,0.6))
    holoColor(1, vec(0,255,0))
    holoParent(1, Body)
    holoCreate(2)
    holoPos(2, BodyPos+vec(-3,0,12))
    holoScale(2, vec(0.3,0.8,0.25))
    holoColor(2, vec(0,255,0))
    holoParent(2, Body)
    holoCreate(3)
    holoPos(3, BodyPos+vec(-3,0,3))
    holoScale(3, vec(0.2,1.5,0.2))
    holoColor(3, vec(0,255,0))
    holoParent(3, Body)
    holoCreate(4)
    holoPos(4, BodyPos+vec(-5,2.2,12))
    holoScale(4, vec(0.18,0.18,0.18))
    holoModel(4, "hqsphere2")
    holoColor(4, vec(255,0,0))
    holoParent(4, Body)
    holoCreate(5)
    holoPos(5, BodyPos+vec(-5,-2.2,12))
    holoScale(5, vec(0.18,0.18,0.18))
    holoModel(5, "hqsphere2")
    holoColor(5, vec(255,0,0))
    holoParent(5, Body)
    holoCreate(6)
    holoPos(6, BodyPos+vec(-3.9,0,12))
    holoScale(6, vec(0.25,0.7,0.20))
    holoColor(6, vec(0,0,255))
    holoParent(6, Body)
    
    O = owner()
    Action = "follow"
}

Ball = entity()
BallPos = Ball:pos()
OPos = O:pos()+vec(0,0,6)
Distance = BodyPos:distance(OPos)
BallDistance = BodyPos:distance(BallPos)
LS = O:lastSaid():explode(" "):string(1)

if (LS:left(1) == "!") {
    if (LS == "!follow") { Action = "follow"}
    if (LS == "!stay") { Action = "stay" }
    if (LS == "!fetch") { Action = "fetch" }
    if (LS == "!owner") { O = findPlayerByName(O:lastSaid():explode(" "):string(2)) }
}

if (Action == "follow") {
    if (Distance > 75) {
        BodyPos-=holoEntity(0):angles():forward()*(Distance/100)+Body:vel():length()
        BodyAng=(BodyPos - OPos):toAngle()
    }
}

if (Action == "stay") {
    BodyPos=BodyPos
}

if (Action == "fetch") {
        if (BallDistance > 20) {
            BodyPos-=holoEntity(0):angles():forward()*(BallDistance/10)+Body:vel():length()
            BodyAng=(BodyPos - BallPos):toAngle()
        }
    if (FetchBall == 0) {
        if (BallDistance <= 20) {
            FetchBall = 1
        }
    }
    
    if (FetchBall == 1) {
        if (BallDistance < 25) {
            Ball:applyForce((OPos-BallPos)/2)
        }
    }
}

holoPos(0, BodyPos)
holoAng(0, BodyAng)
