using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BeardedManStudios.Forge.Networking.Generated;
using BeardedManStudios.Forge.Networking;
using System;

public class NetworkSyncPhysics : NetworkSyncPhysicsBehavior {

    [System.Serializable] private enum ENetworkPriority
    {
        VeryHigh,
        High,
        Medium,
        Low
    }

    [SerializeField] private ENetworkPriority networkPriority;

    [Tooltip("How many times per second should the object be updated.")]
    [SerializeField] [Range(0,9)]private float updateRateInSeconds;

    private float nextUpdateTime = 0;
    [SerializeField] private float smoothTime = 10;

   
    private Rigidbody rb;

    private Vector3 predictedPosition;
    private Quaternion predictedRotation;

    private Vector3 positionOnServer;
    private Quaternion rotationOnServer;

    private bool canUpdateTransform = true;
    private float updateTimer = 0;

    // Use this for initialization
    void Start ()
    {
        rb = GetComponent<Rigidbody>();

        if(!networkObject.IsOwner)
        {
           // rb.isKinematic = true;
        }
	}

    private void Update()
    {
        updateTimer += Time.fixedDeltaTime;
        
        if(updateTimer >= updateRateInSeconds)
        {
            updateTimer = 0;
            canUpdateTransform = true;
        }

        if (networkObject.IsServer && canUpdateTransform)
        {
            canUpdateTransform = false;
            networkObject.SendRpc(RPC_SYNC_PHYSICS_TRANSFORM,Receivers.AllProximity,transform.position,transform.rotation);
        }
        else
        {
            predictedPosition = Vector3.Lerp(transform.position, positionOnServer, Time.fixedDeltaTime * smoothTime);
            predictedRotation = Quaternion.Lerp(transform.rotation, rotationOnServer, Time.fixedDeltaTime * smoothTime);

            rb.MovePosition(predictedPosition);
            rb.MoveRotation(predictedRotation);
        }
    }

    public override void SyncPhysicsTransform(RpcArgs args)
    {
        positionOnServer = args.GetNext<Vector3>();
        rotationOnServer = args.GetNext<Quaternion>();
    }
}
