using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Diagnostics;
using Unity.Netcode;

public class CharacterControl : NetworkBehaviour
{
    // Start is called before the first frame update

    public Rigidbody2D characterRB;
    public GameObject characterGO;
    public GameObject massBorder;
    public GameObject bow;
    public GameObject pivot;
    public GameObject center;
    public GameObject arrowPrefab;
    public bool isHoldingL = true;
    public PlayerController.Controller playerController;
    public Bow.PlayerBow playerBow;
    public Arrow.PlayerArrow playerArrow;
    public SpriteRenderer _renderer;
    private float jumpForce = 10;
    private float moveForce = 2;
    Vector3 moveDirection;

    private int rotationDirection;

    void HandleMovement()
    {
        if (IsLocalPlayer)
        {
            if (pivot.transform.rotation.z >= -180 && pivot.transform.rotation.z < 180)
            {
                rotationDirection = -1;
            }
            else
            {
                rotationDirection = 1;
            }

            if (Input.GetKey(KeyCode.Q))
            {
                pivot.transform.RotateAround(transform.position, new Vector3(0, 0, -1 * rotationDirection), 300 * Time.deltaTime);
                //Debug.Log("rotating LEFT");
            }
            else if (Input.GetKey(KeyCode.E))
            {
                pivot.transform.RotateAround(transform.position, new Vector3(0, 0, 1 * rotationDirection), 300 * Time.deltaTime);
                //Debug.Log("rotating RIGHT");
            }

            if (Input.GetKeyDown(KeyCode.W))
            {
                characterRB.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
            }
            else if (Input.GetKey(KeyCode.A))
            {
                transform.localRotation = Quaternion.Euler(0, 180, 0);
                characterRB.AddForce(Vector2.left * moveForce, ForceMode2D.Force);
            }
            else if (Input.GetKey(KeyCode.D))
            {
                transform.localRotation = Quaternion.Euler(0, 0, 0);
                characterRB.AddForce(Vector2.right * moveForce, ForceMode2D.Force);
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (IsServer && IsLocalPlayer)
        {
            HandleMovement();
        } else
        {
            MoveServerRPC();
        }
    }

    [ServerRpc(RequireOwnership = false)]
    private void MoveServerRPC()
    {
        Debug.Log("Loggin");
        HandleMovement();
    }
}