using SepehrFlightApiSampleClient.BuiltinTypeExtensions;

namespace SepehrFlightApiSampleClient.ApiException
{
    public class Deserializer
    {
        public static void DeserializeResponseAndThrowException(string errorContent)
        {
            // faghat zamani ke khode application sepehr error barmigardone, ma mitonim
            // ba estefadeh az class WebApiException on error ro deserialize konim va
            // be data parse shode dastresi pida konim, vali zamani ke ye chize dge(masalan network)
            // baese be vojod omadane error shode bashe, dige error ba format WebApiException
            // bar nemigarde ke alan betonim ba asase on deserialize anjam bedim.
            // baraye hamin inja try/catch gozashtim ke in mozo ro handle kone

            ResponseModel exception;
            try
            {
                exception = errorContent.DeserializeFromJson<ResponseModel>();
            }
            catch
            {
                // yani error az noe WebApiException nabode
                throw new WebApiException(
                    errorMessage: errorContent,
                    exceptionType: "Known_Exception_Type",
                    traceId: "Not available");
            }

            throw new WebApiException(
                errorMessage: exception.ErrorMessage,
                exceptionType: exception.ExceptionType,
                traceId: exception.TraceId);
        }
    }
}
