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

public class Building : MonoBehaviour {

    public Text title;

    public bool unplaced = true;

    public int bType;

    public AudioSource dropSound;

    private int pay = 1000;

    private GameMenu gm;

    void Start()
    {
        gm = GameObject.Find("ViewController").GetComponent<GameMenu>();
    }

    void Update()
    {
        if (unplaced)
        {
            int groundLayerMask = 1 << 8;

            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(
                ray,
                out hit,
                Mathf.Infinity,
                groundLayerMask
            ))
            {
                gameObject.transform.position = new Vector3(
                    (float) Math.Round(hit.point.x / 2.2) * 2.2f,
                    hit.point.y + 4,
                    (float) Math.Round(hit.point.z / 2.2) * 2.2f
                );
            }

            if (Input.GetMouseButtonDown(0))
            {
                unplaced = false;
                gameObject.transform.position = new Vector3(
                    gameObject.transform.position.x,
                    1,
                    gameObject.transform.position.z
                );

                GameMenu gm = GameObject.Find("ViewController").GetComponent<GameMenu>();
                gm.buildEvent.Invoke(bType);
                gm.openMenu.SetActive(true);
                dropSound.Play();
                if (bType == 1) InvokeRepeating("PayPlayer", 1.0f, 1.0f);
            }
        }
    }

    void PayPlayer()
    {
        gm.money += pay;
    }
}
