﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MGSF
{
    /// <summary>
    /// Request / response between client and server
    /// </summary>
    class Сommunication
    {
        /// <summary>
        /// Request from player
        /// </summary>
        public class Request
        {
            /// <summary>
            /// Query Parameters
            /// </summary>
            JObject variables;

            /// <summary>
            /// Raw request format
            /// </summary>
            public string Source;

            /// <summary>
            /// Request from player
            /// </summary>
            /// <param name="data">JSON Data</param>
            public Request(string data)
            {
                try
                {
                    Source = data;
                    // Trying to deserialize JSON Data ...
                    variables = JsonConvert.DeserializeObject<JObject>(data);
                }
                catch
                {
                    // In the case of a data deserialization error, we denote the list of parameters as null.
                    variables = null;
                }
            }

            /// <summary>
            /// Gives access to a collection of parameters
            /// </summary>
            /// <param name="name">Parameter name</param>
            public JToken this[string name]
            {
                get
                {
                    try
                    {
                        // Try to return the parameter you are looking for ...
                        return variables[name];
                    }
                    catch
                    {
                        // In case of an error, returns the parameter as null.
                        return null;
                    }
                }
            }
        }

        public enum MessageType { Status, Command, Warning, Error, ServerError }

        public class Responce
        {
            /// <summary>
            /// Response Type
            /// </summary>
            [JsonProperty("type")]
            public string Type;

            /// <summary>
            /// Event name
            /// </summary>
            [JsonProperty("eventName")]
            public string EventName;

            /// <summary>
            /// Data
            /// </summary>
            [JsonProperty("data")]
            JObject Data;

            public Responce(MessageType type, string eventName, JObject data)
            {
                Type = type.ToString();
                EventName = eventName;
                Data = data;
            }
        }
    }
}
