/*
 * SnapTrade
 *
 * Connect brokerage accounts to your app for live positions and trading
 *
 * The version of the OpenAPI document: 1.0.0
 * Contact: efpyi@example.com
 * Generated by: https://konfigthis.com
 */


using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = SnapTrade.Net.Client.OpenAPIDateConverter;
using System.Reflection;

namespace SnapTrade.Net.Model
{
    /// <summary>
    /// AuthenticationLoginSnapTradeUser200Response
    /// </summary>
    [JsonConverter(typeof(AuthenticationLoginSnapTradeUser200ResponseJsonConverter))]
    [DataContract(Name = "Authentication_loginSnapTradeUser_200_response")]
    public partial class AuthenticationLoginSnapTradeUser200Response : AbstractOpenAPISchema, IEquatable<AuthenticationLoginSnapTradeUser200Response>, IValidatableObject
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationLoginSnapTradeUser200Response" /> class
        /// with the <see cref="LoginRedirectURI" /> class
        /// </summary>
        /// <param name="actualInstance">An instance of LoginRedirectURI.</param>
        public AuthenticationLoginSnapTradeUser200Response(LoginRedirectURI actualInstance)
        {
            this.IsNullable = false;
            this.SchemaType= "oneOf";
            this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null.");
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationLoginSnapTradeUser200Response" /> class
        /// with the <see cref="EncryptedResponse" /> class
        /// </summary>
        /// <param name="actualInstance">An instance of EncryptedResponse.</param>
        public AuthenticationLoginSnapTradeUser200Response(EncryptedResponse actualInstance)
        {
            this.IsNullable = false;
            this.SchemaType= "oneOf";
            this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null.");
        }


        private Object _actualInstance;

        /// <summary>
        /// Gets or Sets ActualInstance
        /// </summary>
        public override Object ActualInstance
        {
            get
            {
                return _actualInstance;
            }
            set
            {
                if (value.GetType() == typeof(EncryptedResponse))
                {
                    this._actualInstance = value;
                }
                else if (value.GetType() == typeof(LoginRedirectURI))
                {
                    this._actualInstance = value;
                }
                else
                {
                    throw new ArgumentException("Invalid instance found. Must be the following types: EncryptedResponse, LoginRedirectURI");
                }
            }
        }

        /// <summary>
        /// Get the actual instance of `LoginRedirectURI`. If the actual instance is not `LoginRedirectURI`,
        /// the InvalidClassException will be thrown
        /// </summary>
        /// <returns>An instance of LoginRedirectURI</returns>
        public LoginRedirectURI GetLoginRedirectURI()
        {
            return (LoginRedirectURI)this.ActualInstance;
        }

        /// <summary>
        /// Get the actual instance of `EncryptedResponse`. If the actual instance is not `EncryptedResponse`,
        /// the InvalidClassException will be thrown
        /// </summary>
        /// <returns>An instance of EncryptedResponse</returns>
        public EncryptedResponse GetEncryptedResponse()
        {
            return (EncryptedResponse)this.ActualInstance;
        }

        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class AuthenticationLoginSnapTradeUser200Response {\n");
            sb.Append("  ActualInstance: ").Append(this.ActualInstance).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public override string ToJson()
        {
            return JsonConvert.SerializeObject(this.ActualInstance, AuthenticationLoginSnapTradeUser200Response.SerializerSettings);
        }

        /// <summary>
        /// Converts the JSON string into an instance of AuthenticationLoginSnapTradeUser200Response
        /// </summary>
        /// <param name="jsonString">JSON string</param>
        /// <returns>An instance of AuthenticationLoginSnapTradeUser200Response</returns>
        public static AuthenticationLoginSnapTradeUser200Response FromJson(string jsonString)
        {
            AuthenticationLoginSnapTradeUser200Response newAuthenticationLoginSnapTradeUser200Response = null;

            if (string.IsNullOrEmpty(jsonString))
            {
                return newAuthenticationLoginSnapTradeUser200Response;
            }
            int match = 0;
            List<string> matchedTypes = new List<string>();

            try
            {
                // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize
                if (typeof(EncryptedResponse).GetProperty("AdditionalProperties") == null)
                {
                    newAuthenticationLoginSnapTradeUser200Response = new AuthenticationLoginSnapTradeUser200Response(JsonConvert.DeserializeObject<EncryptedResponse>(jsonString, AuthenticationLoginSnapTradeUser200Response.SerializerSettings));
                }
                else
                {
                    newAuthenticationLoginSnapTradeUser200Response = new AuthenticationLoginSnapTradeUser200Response(JsonConvert.DeserializeObject<EncryptedResponse>(jsonString, AuthenticationLoginSnapTradeUser200Response.AdditionalPropertiesSerializerSettings));
                }
                matchedTypes.Add("EncryptedResponse");
                match++;
            }
            catch (Exception exception)
            {
                // deserialization failed, try the next one
                System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into EncryptedResponse: {1}", jsonString, exception.ToString()));
            }

            try
            {
                // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize
                if (typeof(LoginRedirectURI).GetProperty("AdditionalProperties") == null)
                {
                    newAuthenticationLoginSnapTradeUser200Response = new AuthenticationLoginSnapTradeUser200Response(JsonConvert.DeserializeObject<LoginRedirectURI>(jsonString, AuthenticationLoginSnapTradeUser200Response.SerializerSettings));
                }
                else
                {
                    newAuthenticationLoginSnapTradeUser200Response = new AuthenticationLoginSnapTradeUser200Response(JsonConvert.DeserializeObject<LoginRedirectURI>(jsonString, AuthenticationLoginSnapTradeUser200Response.AdditionalPropertiesSerializerSettings));
                }
                matchedTypes.Add("LoginRedirectURI");
                match++;
            }
            catch (Exception exception)
            {
                // deserialization failed, try the next one
                System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into LoginRedirectURI: {1}", jsonString, exception.ToString()));
            }

            if (match == 0)
            {
                throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined.");
            }
            else if (match > 1)
            {
                throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes);
            }

            // deserialization is considered successful at this point if no exception has been thrown.
            return newAuthenticationLoginSnapTradeUser200Response;
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="input">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object input)
        {
            return this.Equals(input as AuthenticationLoginSnapTradeUser200Response);
        }

        /// <summary>
        /// Returns true if AuthenticationLoginSnapTradeUser200Response instances are equal
        /// </summary>
        /// <param name="input">Instance of AuthenticationLoginSnapTradeUser200Response to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(AuthenticationLoginSnapTradeUser200Response input)
        {
            if (input == null)
                return false;

            return this.ActualInstance.Equals(input.ActualInstance);
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            unchecked // Overflow is fine, just wrap
            {
                int hashCode = 41;
                if (this.ActualInstance != null)
                    hashCode = hashCode * 59 + this.ActualInstance.GetHashCode();
                return hashCode;
            }
        }

        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            yield break;
        }
    }

    /// <summary>
    /// Custom JSON converter for AuthenticationLoginSnapTradeUser200Response
    /// </summary>
    public class AuthenticationLoginSnapTradeUser200ResponseJsonConverter : JsonConverter
    {
        /// <summary>
        /// To write the JSON string
        /// </summary>
        /// <param name="writer">JSON writer</param>
        /// <param name="value">Object to be converted into a JSON string</param>
        /// <param name="serializer">JSON Serializer</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteRawValue((string)(typeof(AuthenticationLoginSnapTradeUser200Response).GetMethod("ToJson").Invoke(value, null)));
        }

        /// <summary>
        /// To convert a JSON string into an object
        /// </summary>
        /// <param name="reader">JSON reader</param>
        /// <param name="objectType">Object type</param>
        /// <param name="existingValue">Existing value</param>
        /// <param name="serializer">JSON Serializer</param>
        /// <returns>The object converted from the JSON string</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if(reader.TokenType != JsonToken.Null)
            {
                return AuthenticationLoginSnapTradeUser200Response.FromJson(JObject.Load(reader).ToString(Formatting.None));
            }
            return null;
        }

        /// <summary>
        /// Check if the object can be converted
        /// </summary>
        /// <param name="objectType">Object type</param>
        /// <returns>True if the object can be converted</returns>
        public override bool CanConvert(Type objectType)
        {
            return false;
        }
    }

}
