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

public class DingleBopScript : MonoBehaviour
{


    [Header("Dial values")]
    [SerializeField]
    [Range(0, 100)]
    private float value;

    private bool isBeingDragged = false;
    
    SpriteRenderer spriteRenderer;
    Vector2 cursorPoint = new Vector2();

    GameObject dialRenderer;

    float bias = 0;

    int tick = 0;

    void Start()
    {
        bias = (Random.value - 0.5f);

        
        dialRenderer = gameObject.transform.GetChild(1).gameObject;
        setValue(value);


    }


    private void OnMouseDown()
    {
        isBeingDragged = true;
        cursorPoint = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    }

    private void OnMouseUp()
    {
        isBeingDragged = false;
    }

    private void OnMouseDrag()
    {
        // Get the distance dragged since last update
        Vector2 dragDistance = new Vector2(Input.mousePosition.x, Input.mousePosition.y) - cursorPoint;

        // Modifier for how fast the dial should move when dragged
        float dragWidth = 0.5f;

        // Apply the rotation and clamp the output to 45 < x < 335         
        //Debug.Log("Old value: " + value + "   New value: " + (value + (dragDistance.x * dragWidth)));
        setValue(value - (dragDistance.x * dragWidth));

        // Remember the last mouse point again
        cursorPoint = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    }
    public float getValue()
    {
        return value;
    }

    public void setValue(float newValue)
    {
        // Clamp value to valid range
        this.value = Mathf.Clamp(newValue, 0, 100);

        // Set the rotation
        dialRenderer.transform.rotation = Quaternion.Euler(0, 0, 45 + ((value / 100) * 270));

        // Update the "progress"bar
        //this.transform.parent.GetChild(1).transform.localScale = new Vector3(1 - (value / 100), 1f, 1f);

    }

    private void FixedUpdate()
    {
        tick++;
        if (tick > 10)
        {

            tick = 0;
            // If it is not being interacted with let it randomly wobble
            if (!isBeingDragged)
            {
             //   setValue(value + (((Random.value - 0.5f) + bias) * 3));
            }
        }
    }

}
