using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class TabSwitchFormField : MonoBehaviour {

    public TMP_InputField[] fields;
    int currentFieldIndex = -1;

	// Use this for initialization
	void Start () {
        currentFieldIndex = -1;
    }
	
	// Update is called once per frame
	void Update () {
        // if no input fields there's nothing to do
        if (fields.Length == 0)
            return;

        // find out if the player has clicked any input fields or not
        bool noneFocused = true;
        for(int i = 0; i < fields.Length; i++) {
            if (fields[i].isFocused) {
                currentFieldIndex = i;
                noneFocused = false;
                break;
            }
        }

        // if the player clicked off of a input field they no longer have any focused so we need to handle that case
        if (noneFocused) {
            currentFieldIndex = -1;
        }

        if (Input.GetKeyDown(KeyCode.Tab)) {
            CycleInputFields();
        }
	}

    void CycleInputFields() {

        // if no current field is focused then we should just focus on the first one
        if (currentFieldIndex == -1) {
            FocusOnFieldAtIndex(0);
            return;
        }

        currentFieldIndex++;
        if (currentFieldIndex >= fields.Length) {
            currentFieldIndex = 0;
        }
        FocusOnFieldAtIndex(currentFieldIndex);
    }

    // focus on the field at the given index and update currentFieldIndex accordingly
    void FocusOnFieldAtIndex(int index) {
        fields[index].Select();
        fields[index].ActivateInputField();
        currentFieldIndex = index;
    }
}
