﻿using System.Net;
using DarkRift.Client.Unity;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Dissonance.Integrations.DarkRift2.Demo
{
    public class StateManager : MonoBehaviour
    {
        #region state manager setup
        private interface IState
        {
            void Awake();

            [NotNull] IState Update();        
        }

        private IState _state;
        private IState _nextState;

        private void Awake()
        {
            _state = new InMenu();
            _nextState = _state;
            DontDestroyOnLoad(gameObject);
        }

        private void OnGUI()
        {
            _nextState = _state.Update();
        }

        private void Update()
        {
            if (_state != _nextState)
            {
                _nextState.Awake();
                _state = _nextState;
            }
        }
        #endregion

        #region states
        private class InMenu : IState
        {
            private string _serverIp = "127.0.0.1";
            private string _port = "4296";

            public void Awake() { }

            public IState Update()
            {
                using (new GUILayout.AreaScope(new Rect(20, 20, 200, 200)))
                {
                    _serverIp = GUILayout.TextField(_serverIp);
                    _port = GUILayout.TextField(_port);
                    if (GUILayout.Button("Connect to Server"))
                    {
                        var client = FindObjectOfType<UnityClient>();
                        client.Address = IPAddress.Parse(_serverIp);
                        client.Port = ushort.Parse(_port);
                        client.enabled = true;

                        return new LoadWorld();
                    }
                }

                return this;
            }
        }

        private class LoadWorld : IState
        {
            public void Awake()
            {
                SceneManager.LoadScene("DarkRift2 Game World", LoadSceneMode.Additive);
            }

            public IState Update()
            {
                return new Client();
            }
        }

        private class Client
            : IState
        {
            public void Awake()
            {
                
            }

            public IState Update()
            {
                GUILayout.Label("Game Scene");

                return this;
            }
        }
        #endregion
    }
}
