using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem;

public class DisplaySwitchController : MonoBehaviour
{
    [SerializeField] public InputActionReference inputAction;

    private List<DisplayIdentifier> d1List = new List<DisplayIdentifier>();
    private List<DisplayIdentifier> d2List = new List<DisplayIdentifier>();

    private int mainDisplay = 0;

    private void Start()
    {
        Init();
        ApplyChanges();
    }

    private void Init()
    {
        mainDisplay = PlayerPrefs.GetInt("Display_Settings", 0);
        var tmpdisplays = FindObjectsOfType<DisplayIdentifier>().ToList();

        d1List = tmpdisplays.Where(x => x.ID == DisplayID.Display_1).ToList();
        d2List = tmpdisplays.Where(x => x.ID == DisplayID.Display_2).ToList();
    }

    private void Update()
    {
        if (inputAction.action.triggered)
        {
            SwapDisplays();
        }
    }

    [ContextMenu("Swap Displays")]
    private void SwapDisplays()
    {
        if (mainDisplay == 0)
            mainDisplay = 1;
        else
            mainDisplay = 0;

        PlayerPrefs.SetInt("Display_Settings", mainDisplay);

        ApplyChanges();
    }

    private void ApplyChanges()
    {
        mainDisplay = PlayerPrefs.GetInt("Display_Settings", 0);

        switch (mainDisplay)
        {
            case 0:
                {
                    d1List.ForEach(x => x.SetId(0));
                    d2List.ForEach(x => x.SetId(1));
                }
                break;
            case 1:
                {
                    d1List.ForEach(x => x.SetId(1));
                    d2List.ForEach(x => x.SetId(0));
                }
                break;
        }
    }
}