using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using EyeSkills;

public class AssetSwitcher : MonoBehaviour {

    private List<string> assetNames = new List<string>();
    private int assetIndex=0;
    public bool autoRun = false;

    public void SwitchAssetsToNamed(string selection){

        if (selection == null) selection = "asset-default"; //make sure that we at least display something

        GameObject[] gameObjects = Resources.FindObjectsOfTypeAll<GameObject>() as GameObject[];
        foreach (GameObject go in gameObjects)
        {
            if (go.name == selection)
                go.SetActive(true);
            else if (go.name.StartsWith("asset-"))
                go.SetActive(false);
        }
    }

    /// <summary>
    /// Gets the asset names. Pass in the initial selection to set the index correctly
    /// </summary>
    /// <param name="initialSelection">Selection.</param>
    private void GetAssetNames(string initialSelection){
        GameObject[] gameObjects = Resources.FindObjectsOfTypeAll<GameObject>() as GameObject[];
        assetNames = new List<string>();
        foreach (GameObject go in gameObjects)
        {
            if (go.name.StartsWith("asset-")){
                if (!assetNames.Contains(go.name)){
                    assetNames.Add(go.name);
                }
            }                
        }
        //Set initial index
        if ((initialSelection!=null) && assetNames.Contains(initialSelection))
        {
            assetIndex = assetNames.IndexOf(initialSelection);
            Debug.Log("Setting initialSelection for asset swap to index " + assetIndex + " which is named "+assetNames[assetIndex]);
        }
    }

    public void SwitchAssetsToNext(){
        string n;
        if (assetNames.Count>0){

            //Move to next asset
            int newIndex = assetIndex + 1;
            if (newIndex >= assetNames.Count) newIndex = 0; //cycle through the indexes
            assetIndex = newIndex;

            n = assetNames[assetIndex];
            Debug.Log("Switching to asset " + n);
            SwitchAssetsToNamed(n);

        }

    }

	void Start () {

        string selection = "asset-" + PlayerPrefs.GetString("EyeSkills.assetStyle", "default");
        Debug.Log("Asset Switcher selection=" + selection);

        //Prepare our list of discovered asset names
        GetAssetNames(selection);
    
        if (autoRun) {
            SwitchAssetsToNamed(selection);
        }

    }

}
