﻿using UnityEngine;
using System.Collections;

public class PointManager : MonoBehaviour {
    public FireworkManager FireworkManager;
    public GameObject FireworkBtn;

    private GameObject _rangeGameObject;
    private bool _clicked = false;
    private GameObject _createdRange;
    private Vector3 _mousePositionInWorld;

    private void GetMousePosition() {
        var screenPosition = Camera.main.WorldToScreenPoint(transform.position);
        var mousePositionOnScreen = Input.mousePosition;
        mousePositionOnScreen.z = screenPosition.z;
        _mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePositionOnScreen);
    }

    public void Clicked(GameObject obj, FireworkSelf fireworkInfo) {
        _rangeGameObject = obj;
        _clicked = true;
        GetMousePosition();
        _createdRange = Instantiate(_rangeGameObject, _mousePositionInWorld, Quaternion.identity) as GameObject;
        _createdRange.GetComponent<RangeSelf>().Init(fireworkInfo.gameObject);
//        FireworkInfo = null;
    }

    void Update() {
        if (Input.GetMouseButtonUp(1)) {
            if (_clicked) {
                Destroy(_createdRange);
            }
            _clicked = false;
            _rangeGameObject = null;
        }
        if (_clicked) {
            GetMousePosition();
            _createdRange.transform.position = _mousePositionInWorld;
            if (Input.GetMouseButtonUp(0) && _mousePositionInWorld.y > -8) {
                _clicked = false;
                _createdRange.GetComponent<RangeSelf>().Show();
                _createdRange.GetComponent<AudioSource>().Play();
                FireworkManager.AddFirework(_createdRange);
                FireworkBtn.GetComponent<FireworkClick>().StartCool();
                _createdRange = null;
            }
        }
    }
}
