﻿using System;
#if SILVERLIGHT
using System.Json;
#endif
using SuperMap.Web.Resources;

namespace SuperMap.Web.Service
{
    /// <summary>${mapping_ServiceException_Tile}</summary>
    public sealed class ServiceException : Exception
    {
        internal ServiceException(int code, string message)
            : base(message)
        {
            ErrorMsg = message;
            Code = code;
        }

        
        internal static ServiceException CreateFromJSON(string json)
        {
            #if SILVERLIGHT
            if (json.Length > 0)
            {
                //{"succeed":false,"error":{"errorMsg":"param point2Ds must  contains at least two Point2D;","code":400}}
                JsonObject jsonObject = null;
                try
                {
                    jsonObject = (JsonObject)JsonValue.Parse(json);
                }
                catch (Exception)
                {
                    return null;
                }

                if (jsonObject != null && jsonObject.ContainsKey("succeed") && !((bool)jsonObject["succeed"]))
                {
                    if (jsonObject.ContainsKey("error") && jsonObject["error"].ContainsKey("errorMsg") && jsonObject["error"].ContainsKey("code"))
                    {
                        int code = (int)jsonObject["error"]["code"];
                        string errorMSG = (string)jsonObject["error"]["errorMsg"];

                        return new ServiceException(code, errorMSG);
                    }
                    //IS.NET 提取等值面和等值线的错误结果 
                    //{"succeed":false,"resultDataset":"","message":"提取等值线操作发生错误：“pointPositions.Length != pointValues.Length”。"}
                    else if (jsonObject.ContainsKey("message"))
                    {
                        return new ServiceException(002, jsonObject["message"]);
                    }
                    else
                    {
                        return new ServiceException(002, "处理失败");
                    }
                }
                return null;
            }
#endif
            return new ServiceException(001, ExceptionStrings.ParametersError);
        }


        /// <summary>${mapping_ServiceException_attribute_Code_D}</summary>
        public int Code { get; private set; }
        /// <summary>${mapping_ServiceException_attribute_ErrorMsg_D}</summary>
        public string ErrorMsg { get; private set; }
    }
}
