using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Models
{
    public class Compare
    {
        /// <summary>
        /// Vergleicht die JSON-Datei-Struktur mit dem Vorlagen-Model
        /// </summary>
        /// <returns>Gibt die fehlenden Eigenschaften aus</returns>
        public static IEnumerable<JsonPropertyAttribute> Structure<T>(string filepath)
        {
            foreach (var property in typeof(T).GetProperties())
            {
                if (!Exists(filepath, property.GetPropertyAttribute<JsonPropertyAttribute>().PropertyName))
                {
                    yield return property.GetPropertyAttribute<JsonPropertyAttribute>();
                }
            }
        }


        /// <summary>
        /// Vergleicht die JSON-Datei-Struktur mit dem Vorlagen-Model
        /// </summary>
        /// <returns>Gibt die fehlenden Eigenschaften aus</returns>
        public static IEnumerable<JsonPropertyAttribute> StructurePrevalence(string filepath)
        {
            foreach (var property in new AppList<App>().GetType().GetProperties())
            {
                if (!Exists(filepath, property.GetPropertyAttribute<JsonPropertyAttribute>().PropertyName))
                {
                    yield return property.GetPropertyAttribute<JsonPropertyAttribute>();
                }
            }
        }


        /// <summary>
        /// Vergleicht die JSON-Datei-Struktur mit dem Vorlagen-Model
        /// </summary>
        /// <returns>Gibt die fehlenden Eigenschaften aus</returns>
        public static IEnumerable<string> StructureUserConfig(string filepath)
        {
            foreach (var property in new Config.User().GetType().GetProperties())
            {
                if (!Exists(filepath, property.GetPropertyAttribute<JsonPropertyAttribute>().PropertyName))
                {
                    yield return property.GetPropertyAttribute<JsonPropertyAttribute>().PropertyName;
                }
            }
        }


        private static bool Exists(string path, string propertyname)
        {
            dynamic jsonobject = JsonConvert.DeserializeObject(string.Concat(JObject.Parse(File.ReadAllText(path))), new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Include, Formatting = Formatting.Indented });
            return jsonobject.ContainsKey(propertyname);
        }
    }
}
