﻿using System;
using UnityEngine;

public enum AudioState
{
Move, Take,Taken
}
public class PieceController : MonoBehaviour
{
    // Start is called before the first frame update
    float beginTime;
    bool on = false;
    Vector3 target,ori;
    Animator a;
    GameController gc;
    AudioState aust;
    bool first;
    bool blindOn;
    public bool played;
    public bool Taken;
    float rnd,rndspd;
    public void Move(Vector3 to, GameController g,AudioState aus = AudioState.Move)
    {
        if(a == null)
            a = transform.GetChild(0).GetComponent<Animator>();
        gc = g;
        beginTime = Time.time;
        on = true;
        target = to;
        ori = transform.position;
        a.Play("Move");
        aust = aus;
        first = true;
        played = false;
    }
    void Start()
    {
        a = transform.GetChild(0).GetComponent<Animator>();
        rnd = UnityEngine.Random.Range(5, 10);
        rndspd = UnityEngine.Random.Range(1, 3);
    }
    public void BlindChangeOn()
    {
        /*Outline o = gameObject.AddComponent<Outline>();
        o.OutlineMode = Outline.Mode.OutlineAll;
        o.OutlineWidth = 3;
        o.OutlineColor = Color.red;*/
        blindOn = true;
    }
    public void BlindChangeOff()
    {
        /*Destroy(gameObject.GetComponent<Outline>());
        blindOn = false;*/
    }

    void Update()
    {
        if (blindOn)    
        {
            transform.eulerAngles = transform.eulerAngles + new Vector3(0, 180 * Time.deltaTime*rndspd, 0);
            transform.position = new Vector3(transform.position.x,((float)(Math.Sin((double)(Time.time * rnd)) +1f)*0.06f), transform.position.z);
        }
        if (on)
        {
            float prog = (Time.time - beginTime)/0.5f;
            if (prog > 1)
            {
                prog = 1;
                on = false;
            }
            if (gc != null && prog > 0.8f && !played)
            {
                 played = true;
                if (aust == AudioState.Move)
                    gc.PlaySoundID(Audio.Move + UnityEngine.Random.Range(0, 6));
            }
            if (first)
            {
                first = false;
                if (gc != null)
                {
                    played = false;
                    if (aust == AudioState.Taken)
                        gc.PlaySoundID(Audio.Take);
                }
            }
            transform.position = Vector3.Lerp(ori, target, Mathf.SmoothStep(0, 1, prog));

        }
    }
}
