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

public class PlugController : MonoBehaviour
{
    public float _minSpeed = 1.0f;
    public float _maxSpeed = 5.0f;
    public float _maxDistanceSpeed = 10.0f;
    public float _minDistanceSpeed = 0.6f;

    public float offset = 10.02f;

    private Vector2 _current;
    private bool following;
    private float distance;

    // Start is called before the first frame update
    void Start()
    {
        _current = GetComponent<Transform>().position;
        following = false;
        distance = 0.0f;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && ((Camera.main.ScreenToWorldPoint(Input.mousePosition) - GetComponent<Transform>().position).magnitude <= offset))
        {
            following = true;
        }

        if (Input.GetMouseButtonUp(0))
        {
            following = false;
        }
    }

    void FixedUpdate()
    {
        if (following)
        {
            float _xRel = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - GetComponent<Transform>().position).x;
            float _yRel = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - GetComponent<Transform>().position).y;

            float xSpeed = 0.0f;
            if (Math.Abs(_xRel) > _minDistanceSpeed)
            {
                xSpeed = _xRel * _maxSpeed / _maxDistanceSpeed;
                if (Math.Abs(xSpeed) < _minSpeed) xSpeed = _minSpeed * xSpeed < 0 ? -1.0f : 1.0f;
            }

            float ySpeed = 0.0f;
            if (Math.Abs(_yRel) > _minDistanceSpeed)
            {
                ySpeed = _yRel * _maxSpeed / _maxDistanceSpeed;
                if (Math.Abs(ySpeed) < _minSpeed) ySpeed = _minSpeed * ySpeed < 0 ? -1.0f : 1.0f;
            }
            
            GetComponent<Rigidbody2D>().velocity = new Vector2(xSpeed, ySpeed);

            distance += Vector2.Distance(GetComponent<Transform>().position, _current);
            _current = GetComponent<Transform>().position;

            //Debug.Log("So far: " + distance);
        }
        else
        {

            GetComponent<Rigidbody2D>().velocity = new Vector2(0.0f, 0.0f);
        }


    }

}
