#ifndef _mr_movement_
#define _mr_movement_
objectdef MovememntKeyMap
{
    variable string MoveForwardKey = "w"
}

objectdef MRNavigation
{
    variable bool CampSpotSet = FALSE
    variable bool MoveToRequested = FALSE
    variable point3f MoveToPoint
    variable float Percision = 5

    method SetPercision(float persision)
    {
        Percision:Set[${persision}]
    }

    method MoveTo(point3f point, float minDistance = 1)
    {
        This:BreakCampSpot
        This.Percision:Set[${minDistance}]
        MoveToRequested:Set[TRUE]
        MoveToPoint:Set[${point.X}, ${point.Z}, ${point.Z}]
    }

    method SetCampSpot(point3f point)
    {
        CampSpotSet:Set[TRUE]
        MoveToPoint:Set[${point.X}, ${point.Z}, ${point.Z}]
    }

    method BreakCampSpot()
    {
        CampSpotSet:Set[FALSE]
    }

    method MoveToComplete()
    {
        MoveToRequested:Set[FALSE]
    }
}

variable(global) MRNavigation MRNav
variable MovememntKeyMap MRMoveKeyMap

variable jsonvalue _debounceChecks = "{}";
function Debounce(string command, string id, int interval)
{
    if !${_debounceChecks.Has["${id}"]} || !${_debounceChecks.Get["${id}"]}
    {
        variable weakref commandRef = "${command}"
        _debounceChecks:Set["${id}", TRUE]
        execute ${command}
        TimedCommand ${interval} Script["${Script.Filename}"].Variable["_debounceChecks"]:Erase["${id}"]
    }
}

function FacePoint(point3f point)
{
    call Debounce "face ${point.X} ${point.Z}" "face" 3
}

function MoveTo(point3f point)
{
    
    while ${Math.Distance[${Me.X},${Me.Z},${MRNav.MoveToPoint.X},${MRNav.MoveToPoint.Z}]} > ${MRNav.Percision}
    {
        call FacePoint ${point}

        if !${Me.IsMoving}
        {
            
            call Debounce "press -hold ${MRMoveKeyMap.MoveForwardKey}" "moveForward" 5
        }
        wait 1

        call Debounce "echo Distance ${Math.Distance[${Me.X},${Me.Z},${MRNav.MoveToPoint.X},${MRNav.MoveToPoint.Z}]} > ${MRNav.Percision}" "debugDistance" 5
    }
    press -release ${MRMoveKeyMap.MoveForwardKey}
    MRNav:MoveToComplete
}

function main()
{
    while 1
    {
        if ${MRNav.MoveToRequested} 
        {
            call Debounce "call MoveTo ${MRNav.MoveToPoint}" "move" 5
        }

        if ${MRNav.CampSpotSet}
        {
            call Debounce "call MoveTo ${MRNav.MoveToPoint}" "move" 5
        }
        wait 1
    }

}
#endif