using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json.Serialization;

namespace BukiVedi.GenreBooksSelector
{
    internal class Program
    {
        private static bool IsValidJson(string strInput)
        {
            if (string.IsNullOrWhiteSpace(strInput)) { return false; }
            strInput = strInput.Trim();
            if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
                (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
            {
                try
                {
                    var obj = JToken.Parse(strInput);
                    return true;
                }
                catch (JsonReaderException jex)
                {
                    //Exception in parsing json
                    Console.WriteLine(jex.Message);
                    return false;
                }
                catch (Exception ex) //some other exception
                {
                    Console.WriteLine(ex.ToString());
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        static string JsonCorrection(string file)
        {
            var json = File.ReadAllText(file);
            if (json.StartsWith("{")) return json;
            json = "{\r\n" + json + "}";
            if (IsValidJson(json))
            {
                File.WriteAllText(file, json);
            }
            else
            {
                Console.WriteLine($"Not valid file '{file}'");
            }
            return json;
        }

        static void SearchBooks(string booksFile)
        {
            dynamic data = JsonConvert.DeserializeObject(File.ReadAllText(booksFile));
            foreach (dynamic book in data.books)
            {
                Console.WriteLine(book.title);
            }
        }


        static void Main(string[] args)
        {
            var genre_folder = @"F:\Documents\Python Scripts\bookgenres";
            foreach(var genre in Directory.GetDirectories(genre_folder)) 
            {
                var genre_books = Path.Combine(genre, "books.txt");
                SearchBooks(genre_books);
                foreach (var subgenre in Directory.GetDirectories(genre))
                {
                    var subgenre_books = Path.Combine(subgenre, "books.txt");
                    SearchBooks(subgenre_books);
                }
            }
        }
    }
}
