﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Radical.Project
{
    /// <summary>
    /// http://jekyllrb.com/docs/configuration/#frontmatter-defaults
    /// Do not include:
    /// - Include
    /// - TimeZone
    /// - Encoding
    /// </summary>
    public class SiteConfig
    {
        public const string CONFIG_FILE_NAME = "_config.json";

        public int Port { get; set; }

        public string Source { get; set; }

        public string Destination { get; set; }

        public string Layout { get; set; }

        public List<string> Exclude { get; set; }

        public List<SiteDefault> Defaults { get; set; }

        public SiteConfig()
        {
            Source = ".";
            Destination = "_site";
            Layout = "_layout";
            Port = 12345;

            Exclude = new List<string>();
            Defaults = new List<SiteDefault>
            {
                new SiteDefault
                {
                    Scope = new SiteDefault.SiteScope
                    {
                        Path = ""
                    },
                    Values = new Dictionary<string, string>
                    {
                        {"layout", "_layout"}
                    }
                }
            };
        }

        /// <summary>
        /// Read config file from a given directory
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static SiteConfig ReadFromDirectory(string dir)
        {
            var fileConfig = Path.Combine(dir, CONFIG_FILE_NAME);

            if (!File.Exists(fileConfig))
                throw new ApplicationException("Config file is missing.");

            var config = File.ReadAllText(fileConfig);

            return JsonConvert.DeserializeObject<SiteConfig>(config);
        }
    }

    public class SiteDefault
    {
        public SiteScope Scope { get; set; }

        public Dictionary<string, string> Values { get; set; }


        public SiteDefault()
        {
            Scope = new SiteScope();
            Values = new Dictionary<string, string>();
        }

        public class SiteScope
        {
            [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
            public string Path { get; set; }

            [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
            public string Type { get; set; }
        }
    }
}
