using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LocalPlayer : Player {

    public CharacterController charControl;
    public Animator Animator;

    public float Speed = 5;

    private float animWalkSpeed = 0;

    protected override void Update()
    {
        ApplyGravity();
        ApplyInput();
        Teleport();

        base.Update();
    }

    private void ApplyGravity()
    {
        if (!charControl.isGrounded)
        {
            charControl.SimpleMove(new Vector3(0.0f, -5.0f * Time.deltaTime, 0.0f));
        }
    }

    private void ApplyInput()
    {
        if (Input.GetMouseButton(0))
        {
            Vector3 mousePos = new Vector3(Input.mousePosition.x, 0.0f, Input.mousePosition.y);
            Vector3 screenCentre = new Vector3(Screen.width / 2, 0.0F, Screen.height / 2);
            Vector3 movePos = mousePos - screenCentre;

            movePos.x = movePos.x / Screen.width;
            movePos.z = movePos.z / Screen.height;
            charControl.Move(movePos * Speed * Time.deltaTime);

            animWalkSpeed = Mathf.Clamp01(movePos.magnitude * 3);

            playerModel.transform.LookAt(playerModel.transform.position + movePos, Vector3.up);
        }else if (animWalkSpeed > 0)
        {
            animWalkSpeed -= 0.1f;
        }

        Animator.SetFloat("WalkSpeed", animWalkSpeed);
    }

    void Teleport()
    {
        if (map == null)
            return;

        if (transform.position.x > map.maxX)
        {
            transform.position = new Vector3(map.minX, transform.position.y, transform.position.z);
        }
        else if (transform.position.x < map.minX)
        {
            transform.position = new Vector3(map.maxX, transform.position.y, transform.position.z);
        }
        if (transform.position.z > map.maxZ)
        {
            transform.position = new Vector3(transform.position.x, transform.position.y, map.minZ);
        }
        else if (transform.position.z < map.minZ)
        {
            transform.position = new Vector3(transform.position.x, transform.position.y, map.maxZ);
        }
    }
}
