﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;

public class LootRandomizer : MonoBehaviour {

	public List<GameObject> LootChests;
    public static int CurrentChestIndex = 0;

    // Use this for initialization
    void Start () {
        //chestIndex = 0;
        LootChests = new List<GameObject> ();
		LootChests.Clear ();

		ValidateChests (transform);
        GameGenerator.SetRandomToOldSeed();
        RandomizeLootChests();
	}


	void ValidateChests (Transform source) {
		foreach (Transform child in source) {
            LootChestScript lootChestScript = child.GetComponent<LootChestScript>();
			if (lootChestScript) {
                lootChestScript.chestIndex = CurrentChestIndex++;
				//Debug.LogError("Added chest " + lootChestScript.transform.name + " at " + lootChestScript.transform.position + " to the index as #" + lootChestScript.chestIndex);
				child.gameObject.SetActive (false);
				LootChests.Add (child.gameObject);
			} else if (child.childCount > 0) {
				ValidateChests (child);
			} else if (!lootChestScript && child.tag == "LootChest") {
				//Debug.LogError("Is there a script attached to " + child.name + " at " + child.parent.name + "?");
            }
		}
	}

	void RandomizeLootChests () {
		int totalChests = Random.Range (5, 16);

		if (LootChests.Count >= 7) {
			for (int i = 0; i < totalChests; i++) {
				int selected = Random.Range (0, LootChests.Count);
				LootChests [selected].SetActive (true);
				LootChests.Remove (LootChests [selected]);
				if (LootChests.Count == 0) {
					break;
				}
			}
		} else {
			for (int i = 0; i < LootChests.Count; i++) {
				LootChests [i].SetActive (true);
			}
		}
	}
}
