﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Arugula;
using Arugula.Math;
using Arugula.Audio;

using UnityEngine.InputSystem;

public class Sheep : MonoBehaviour
{
    [MinMax(0.5f, 1.5f)]
    public Vector2 eyeScale;
    public Transform[] eyes;

    public Dice.WeightedGameObject[] accessories;

    public Vector3 moveForce;
    public Vector3 moveTorque;

    public Vector3 turnForce;
    public Vector3 turnTorque;

    [Range(0, 1)]
    public float turnChance;

    Rigidbody rb;

    [PhonicSound]
    public string bleetSound;
    public Phonic.Options bleetOptions;
    private IEnumerator Start()
    {



        transform.Rotate(0, Random.value * 360, 0);

        rb = GetComponent<Rigidbody>();
        foreach (var e in eyes)
        {
            e.localScale = Random.Range(eyeScale.x, eyeScale.y) * Vector3.one;
        }

        var go = Dice.Roll(accessories);
        if (go)
            go.SetActive(true);

        while (true)
        {
            yield return new WaitForSeconds(Random.Range(1f, 3f));

            if (Random.value > turnChance)
                Move();
            else
                Turn(Random.Range(-1f, 1f));

            if (Random.value < 0.1f)
            {
                bleetOptions.position = transform.position;
                Phonic.Play(bleetSound, bleetOptions);
            }
        }
    }

    public void Move()
    {
        Quaternion rot = Quaternion.LookRotation(transform.rotation.GetHeading());
        rb.AddForce(rot * moveForce, ForceMode.VelocityChange);
        rb.AddTorque(rot * moveTorque, ForceMode.VelocityChange);
    }

    public void Turn(float influence)
    {
        Vector3 t = turnTorque * influence;
        Quaternion rot = Quaternion.LookRotation(transform.rotation.GetHeading());
        rb.AddForce(rot * turnForce, ForceMode.VelocityChange);
        rb.AddTorque(rot * t, ForceMode.VelocityChange);
    }

    private void FixedUpdate()
    {
        if (Keyboard.current.spaceKey.wasPressedThisFrame)
            Move();
        if (Keyboard.current.aKey.wasPressedThisFrame)
            Turn(-1);
        else if (Keyboard.current.dKey.wasPressedThisFrame)
            Turn(1);
    }
}
