using Jayrock.Json.Conversion;
using System;
using System.Collections.Generic;
using System.Text;

namespace LJLib.Text.Parser
{
    public sealed class LJParser
    {
        public object JsonParse(Type type, object jsonstr, IDictionary<string, byte[]> files = null)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (jsonstr == null)
            {
                throw new ArgumentNullException("jsonstr");
            }

            if (typeof(string).IsAssignableFrom(jsonstr.GetType()))
            {
                return JsonConvert.Import(type, jsonstr as string, files);
            }
            else
            {
                return JsonConvert.Import(type, ToJson(jsonstr), files);
            }
        }

        public T JsonParse<T>(object jsonstr, IDictionary<string, byte[]> files = null)
        {
            return (T)JsonParse(typeof(T), jsonstr, files);
        }

        public object JsonParse(object jsonstr)
        {
            if (jsonstr == null)
            {
                throw new ArgumentNullException("jsonstr");
            }

            if (typeof(string).IsAssignableFrom(jsonstr.GetType()))
            {
                return JsonConvert.Import(jsonstr as string);
            }
            else
            {
                return JsonConvert.Import(ToJson(jsonstr));
            }
        }

        public string ToJson(object obj, IDictionary<string, byte[]> files = null, string prefix = null)
        {
            StringBuilder sb = new StringBuilder();
            JsonConvert.Export(obj, sb, files, prefix);
            return sb.ToString();
        }
    }
}
