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

public class ClockRotor : MonoBehaviour
{
    public AlarmClock alarmClock;
    
    private Vector2 dragStart;
    private CircleCollider2D dragCollider;

    private float speed = 160f;

    private TimeSpan totalTime = TimeSpan.Zero;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private void OnMouseDown()
    {
        dragStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        
        foreach (CircleCollider2D col in GetComponents<CircleCollider2D>())
        {
            if (col.OverlapPoint(dragStart))
            {
                dragCollider = col;
                break;
            }
        }
    }

    private void OnMouseDrag()
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 delta = mousePos - dragStart;

        float theta = Mathf.Acos(
            (dragStart.sqrMagnitude + mousePos.sqrMagnitude - delta.sqrMagnitude) /
            (2 * dragStart.magnitude * mousePos.magnitude));

        theta = theta * Time.deltaTime * speed;

        if (float.IsNaN(theta))
        {
            return;
        }

        transform.Rotate(Vector3.forward, -theta);
        TimeSpan timeDelta = new TimeSpan((long) Mathf.Round(TimeSpan.TicksPerHour * (theta / 360f)));
        alarmClock.timeUntilAlarm += timeDelta;
        
        dragStart = dragCollider.ClosestPoint(mousePos);
    }
}
