﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;//UIを使用するのに必要
using UnityEngine.SceneManagement;//シーン遷移をするのに必要

public class myQuest : MonoBehaviour {


    //改造2018/07/05
	[SerializeField, HeaderAttribute ("必要な餌の数")]
	public int points;

    //ランダム生成用
    [SerializeField, HeaderAttribute("生成時間間隔")]
    public float genTime;
    float elapsedTime;

    [SerializeField, HeaderAttribute("生成場所範囲")]
    public float posXmax;
    public float posXmin;
    public float posZmax;
    public float posZmin;
    public float posYmax;
    public float posYmin;

    //餌用オブジェクト
    public GameObject baitObj;


	//sound
	[SerializeField, HeaderAttribute ("効果音をここにドロップ")]
	public AudioClip getSound;
	public AudioClip tickSE;


	//default time
	[SerializeField, HeaderAttribute ("カウントダウンの初期時間設定")]
	public int gameTime;
	[SerializeField, HeaderAttribute ("残時間のUItextをドロップ")]
	public Text timeText;
	[SerializeField, HeaderAttribute ("残りの経由地数表示UIをドロップ")]
	public Text nokoriText;

	[SerializeField, HeaderAttribute ("エンディングのシーンファイル名を入力")]
	public string endSceneName;

	//audio source get from this script attached
	AudioSource myaudio;


	// Use this for initialization
	void Start () {

		myaudio =	GetComponent<AudioSource>();
		timeText.text = "残り時間" + gameTime.ToString () + "秒";
		nokoriText.text = "のこり" + points.ToString () + "個";
		//start after nSec
		Invoke("timeCount", 3.5f);

	
	}


	
	// Update is called once per frame
	void Update () {
        //コルーチンでやるのがベターですが，Time.deltaTimeの使い方で
        elapsedTime += Time.deltaTime;

        if (elapsedTime >= genTime)
        {

            float x = Random.Range(posXmin, posXmax);
            float y = Random.Range(posYmin, posYmax);
            float z = Random.Range(posZmin, posZmax);
            Instantiate(baitObj, new Vector3(x, y, z), Quaternion.identity);
            elapsedTime = 0.0f;
        }
	
	}



	//if hit destroy obj

	void RedirectedOnTriggerEnter(Collider mycollider) {
		//Debug.Log (mycollider.gameObject.tag);
		if (mycollider.gameObject.tag == "pointObj") {
			points--;
			nokoriText.text = "のこり" + points.ToString () + "個";
			myaudio.PlayOneShot (getSound, 0.7F);
			Destroy (mycollider.gameObject);

			if (points < 1) {
				//go end
				StopCoroutine("loop");
				Invoke("goEnd", 2f);
			}
		}
	}



	void timeCount(){
		StartCoroutine("loop");

	}


	private IEnumerator loop() {
		while (true) {
			gameTime--;//

			timeText.text = "残り時間" + gameTime.ToString () + "秒";
			myaudio.PlayOneShot(tickSE, 0.7F);
			yield return new WaitForSeconds (1f);
		}
	}


	void goEnd(){
		PlayerPrefs.SetInt ("mytime", gameTime);//save time
		SceneManager.LoadScene (endSceneName);//go end scene
	}



}
