using BukiVedi.Shared.Services;
using FB2Library;
using System.Text;
using ZeroLevel;

namespace TitleReader
{
    internal class Program
    {
        static string ToCsv(string line)
        {
            return line.Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ').Replace(';', ',');
        }
        //222
        static async Task Main(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            var library = new Library();


            //await Tables.UserTag.Write(new BukiVedi.Shared.Entities.UserTag { UserId = "660866a1f944622b13b72017", BookId = "660587c9481e83af64cce15e", Name = "шиза" });
            //await Tables.UserTag.Write(new BukiVedi.Shared.Entities.UserTag { UserId = "660866a1f944622b13b72017", BookId = "6605680a481e83af64c3a7d4", Name = "перечитывать" });
            //await Tables.UserTag.Write(new BukiVedi.Shared.Entities.UserTag { UserId = "660866a1f944622b13b72017", BookId = "66057488481e83af64c802b8", Name = "нараз" });


            /*************** RESCAN LIBRARY ***************/
            // await library.Rescan();
            /**********************************************/


            /*************** REINDEX LIBRARY ***************/
            // await library.Reindex();
            /***********************************************/


            /*************** SEARCH IN LIBRARY ***************/

            foreach (var b in (await library.SearchBooks("гарри поттер и семена смерти")))
            {
                Console.WriteLine(b.Title);
            }

            foreach (var b in (await library.SearchBooks("гарри поттер и дары смерти")))
            {
                Console.WriteLine(b.Title);
            }

            /*************************************************/

            // await Search(library, "29940.fb2");
        }

        static async Task TestDownload()
        {
            var zipLibraryReader = new ZipLibraryReader(@"I:\Library\Flibusta.Net");
            var info = zipLibraryReader.ReadBookInfo(@"I:\Library\Flibusta.Net\fb2-000024-030559.zip", 22273);
            using (var fs = new FileStream(@"H:\test.fb2", FileMode.Create, FileAccess.Write, FileShare.None))
            {
                await zipLibraryReader.Download(@"I:\Library\Flibusta.Net\fb2-000024-030559.zip", 22273, fs);
            }
        }

        static async Task ReadTest()
        {
            int index = 0;
            var zipLibraryReader = new ZipLibraryReader(@"I:\Library\Flibusta.Net");
            foreach (var book in zipLibraryReader.ReadBooks())
            {
                using (var fs = new FileStream(@"H:\" + index + ".epub", FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    await zipLibraryReader.Download(book.ArchivePath, book.ArchiveIndex, fs);
                }
                index++;
            }
        }

        static async Task CreateSampleSet(Library library)
        {
            using (var stream = new FileStream(@"H:\books.csv", FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (TextWriter writer = new StreamWriter(stream))
                {
                    await library.ReadAllBooks(b =>
                    {
                        if (string.IsNullOrWhiteSpace(b.Title) == false && string.IsNullOrWhiteSpace(b.Description) == false)
                        {
                            string authors = string.Empty;
                            if (b.Authors != null)
                            {
                                authors = string.Join(",", b.Authors.Select(a => a.Name));
                            }
                            writer.WriteLine($"{b.Id};{ToCsv(b.Title)};{ToCsv(b.Description)};{ToCsv(b.Genre.Name ?? string.Empty)};{b.Year};{ToCsv(authors)}");
                        }
                        return true;
                    });
                    writer.Flush();
                }
            }
        }

        static async Task TestFB2()
        {
            var path = @"H:\test.fb2";
            var xml = File.ReadAllText(path);
            FB2File file = await new FB2Reader().ReadAsync(xml);
        }

        static async Task Search(Library lib, string title)
        {
            Console.WriteLine($"SEARCH: {title}");
            int index = 0;
            foreach (var book in (await lib.SearchBooks(title)))
            {
                using (var fs = new FileStream(@"H:\" + index + ".fb2", FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    await lib.DownloadToStream(fs, book);
                }
                index++;
                Console.WriteLine($"\t\t{book.Title} ({string.Join(',', book.Authors.Select(a => a.Name))})");
            }
            Console.WriteLine();
            Console.WriteLine("***********************************");
            Console.WriteLine();
        }
    }
}
