﻿using System.Collections;
using System.Collections.Generic;
using System.Net;
using DG.Tweening;
using UnityEngine;
using DarkTonic.MasterAudio;

public class SnakePiece : MonoBehaviour
{

    public JointController jointController;

    // Types
    public bool faster = false;
    public bool switcher = false;

    public float speedIncrease;

    public Snake snake;

    string pieceNameUnconnected = "Piece (Free)";

    public SpringJoint joint;
    public GameObject anchorHelper;
    public bool connected = false;
    public int position;

    public Material matConnected, matConnectedHarmless;

    public DOTweenAnimation animationBeforePickup;


    [SoundGroupAttribute] public string soundCollect;

    // Use this for initialization
    void Start ()
	{

	    RemoveJoint();

	    if (!connected)
	    {

            position = 0;
	        this.gameObject.name = pieceNameUnconnected;
	        if (faster) this.gameObject.name += " [Fast]";
	        if (switcher) this.gameObject.name += " [Switch]";

        }

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

    public void Connect(GameObject go, int arrayPosition, Snake snake)
    {
        go.layer = 9; // Change layer to PieceConnected
        snake.snakeLength++;

        MasterAudio.PlaySound3DAtTransformAndForget(soundCollect,snake.snakeHeadModel.transform);

        if (faster) // Grabbed a faster piece
        {
            animationBeforePickup.DOKill();
            Debug.Log("Go faster");
            snake.controls.moveSpeed += speedIncrease;
        }
        if (switcher)
        {
            animationBeforePickup.DOKill();
            snake.switchedControls = true;
            Debug.Log("Switching controls");
        }
        AddJointComponent();
        joint.connectedBody = go.GetComponent<Rigidbody>();
        position = arrayPosition;
        if (arrayPosition < 4)
        {
            this.GetComponent<Renderer>().material = matConnectedHarmless;
        }
            else
        {
            this.GetComponent<Renderer>().material = matConnected;
        }
    }

    public void RemoveJoint()
    {
        if (this.gameObject.GetComponent<SpringJoint>() == null) return;

        Destroy(this.gameObject.GetComponent<SpringJoint>());
    }

    public void AddJointComponent()
    {
        // Creating SpringJoint component
        this.gameObject.AddComponent<SpringJoint>();
        joint = gameObject.GetComponent<SpringJoint>();

        // Grabs values from spring controller
        jointController.UpdateSettings();
        joint.enableCollision = true;

    }

    public void Bulge(float delay)
    {
        transform.DOScale(new Vector3(1, 1, 1), 0.5f).SetDelay(delay);
    }

    void OnCollisionEnter(Collision collision)
    {
        if (connected) return;
        if (collision.gameObject.CompareTag("Obstacle"))
        {
            Destroy(this.gameObject);
        }
    }

}
