using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;

namespace Knoks.Api.Client
{
    public interface IApiResult
    {
        object Result { get; }
        ApiError Error { get; }
    }

    public class ApiResult<T> : IApiResult
    {
        public HttpResponseMessage HttpResponse;
        public string Json;
        public ApiResponse<T> ApiResponse;
        public T Object { get { return ApiResponse.Result; } }

        public object Result { get { return ApiResponse.Result; } }
        public ApiError Error { get { return ApiResponse.Error; } }

        public ApiResult(HttpResponseMessage httpResponse, string json)
        {
            HttpResponse = httpResponse;
            Json = json;
            ApiResponse = JsonConvert.DeserializeObject<ApiResponse<T>>(json);
        }

        public bool IsValidJson(string schemaFilePath)
        {
            IList<string> err;
            return IsValidJson(schemaFilePath, out err);
        }

        public bool IsValidJson(string schemaFilePath, out IList<string> err)
        {
            var jSchema = JSchema.Parse(File.ReadAllText(schemaFilePath));
            return JsonConvert.DeserializeObject<JObject>(Json).IsValid(jSchema, out err);
        }
    }
}
