﻿namespace ECS.GameObjectECS
{
    using ECS;
    using ECS.Controllers;
    using UnityEngine;

    [ECS.RequireComponent(typeof(GameObjectComp))]
    public class PlayerMovementComp : ECS.Component
    {
        public float sensitivity = 25.0f;
        public float moveSpeed = 10.0f;
        public float jumpSpeed = 7.5f;
        public float gravity = Physics.gravity.y;
        public float rotationRange = 80.0f;

        private CharacterController characterController;

        private float verticalRotation = 0.0f;

        private float verticalVelocity = 0.0f;

        private GameObjectECSBridge bridge;

        public override void Start()
        {
            this.bridge = this.GetComponent<GameObjectComp>().bridge;

            this.characterController = this.bridge.gameObject.GetComponent<CharacterController>();

            this.bridge.OnUpdate += this.Update;
        }

        public void Update()
        {
            if (ECSController.Instance.active)
            {
                // Rotation
                this.bridge.transform.Rotate(new Vector3(
                    0.0f,
                    Input.GetAxis("Mouse X") * this.sensitivity,
                    0.0f));

                this.verticalRotation -= Input.GetAxis("Mouse Y") * this.sensitivity;
                this.verticalRotation = Mathf.Clamp(this.verticalRotation, -this.rotationRange, this.rotationRange);
                Camera.main.transform.localRotation = Quaternion.Euler(this.verticalRotation, 0.0f, 0.0f);

                // Movement
                Vector3 movement = new Vector3(
                    Input.GetAxis("Horizontal"),
                    0.0f,
                    Input.GetAxis("Vertical"));

                if (this.characterController.isGrounded)
                {
                    if (Input.GetButtonDown("Jump"))
                    {
                        this.verticalVelocity = this.jumpSpeed;
                    }
                    else
                    {
                        this.verticalVelocity = this.gravity;
                    }
                }
                else
                {
                    this.verticalVelocity += this.gravity * Time.deltaTime;
                }

                movement.y = this.verticalVelocity;

                movement = this.bridge.transform.rotation * movement;

                this.characterController.Move(movement);
            }
        }
    }
}
