#include <iostream>
#include <fstream>
#include <ctime>
#include <algorithm>

#ifdef WIN32
#include <direct.h>
#define mkdir(dir, mode) _mkdir(dir)
#endif

#include "datfile.h"
using namespace LOTRO_DAT;

void InitializeFileLoop(DatFile& file) {
    while (!file.Initialized()) {
        std::cout << "Please, tell, where the .dat file is\n";
        std::cout << "Enter path to file (including filename): ";
        std::string filename;
        std::getline(std::cin, filename);

        // std::cout << "Enter file id: ";
        // std::string file_id_str;
        // std::getline(std::cin, file_id_str);
        // int file_id = 0;
        // try {
        //     file_id = stoi(file_id_str);
        // } catch (std::invalid_argument) {
        //     std::cout << "Invalid dat file id entered!\n\n";
        //     continue;
        // }

        std::cout << "Opening file " << filename << std::endl;

        bool result = file.Init(filename); // TODO: INIT WITH DAT FILE ID
        if (!result) {
            std::cout << "Dat initialisation failed.\nPlease enter path to .dat file once more\n";
        }
    }
}

int main() {
    std::cout.precision(1);
    std::cout << std::fixed;
    std::cout << "Endevir's LotRO .dat patcher ver. 1.0.0" << std::endl;
    freopen("patcher_errors.log", "w", stderr);

    setbuf(stdout, nullptr);
    setbuf(stderr, nullptr);

    setvbuf (stdout, nullptr, _IONBF, BUFSIZ);
    setvbuf (stderr, nullptr, _IONBF, BUFSIZ);

    std::cout << "Hello! I'm a basic shell version of .dat file patcher. I can open .dat file directly, "
            "if you write path to it (with name of file) in file \"dat_file_path.txt\"\n";
    
    DatFile file(0);

    std::ifstream in("dat_file_path.txt");
    if (!in.fail()) {
        std::string filename;
        std::getline(in, filename);

        std::string file_id_str;
        std::getline(in, file_id_str);
        int file_id = 0;
        try {
            file_id = stoi(file_id_str);
        } catch (std::invalid_argument) {
            file_id = -1;
            std::cout << "Invalid file_id on second line of file dat_file_path.txt!\n\n";
        }

        if (file_id != -1) {
            std::cout << "Using .dat file from dat_file_path.txt...\n";
            std::cout << "Opening file " << filename << " with id = " << file_id << std::endl;
            bool result = file.Init(filename);
            if (!result) {
                std::cout << "Dat initialisation failed.\n";
            }
        }
    }

    InitializeFileLoop(file);
    std::cout << "Great! File initialised successfully!\n";

    while (true) {
        std::cout << "Please, choose, what should I do. I can patch datfile from database to .dat file (enter 1) or exit (enter -1)\n";

        std::cout << "Enter number of command (1-10): ";
        std::string command;
        std::getline(std::cin, command);
        int cmd = -10;
        try {
            cmd = stoi(command);
        } catch (std::invalid_argument) {
            std::cout << "Invalid command entered!\n\n";
            continue;
        }

        if (cmd == -1) {
            std::cout << "Exiting. Thanks for using me!\n";
            file.Deinit();
            break;
        }

        if (cmd == 1) {
            std::cout << "You've chosen to patch database! Write name of database file (it should be in the same "
                    "directory), of enter 0 to return to main dialogue.\n";
            while (true) {
                std::cout << "Enter name of file or 0: ";
                std::string dbname;
                std::getline(std::cin, dbname);

                if (dbname == std::to_string(0)) {
                    std::cout << "Okay, returning back...\n\n";
                    break;
                }

                Database db;

                std::cout << "Opening database... " << dbname << std::endl;

                if (!db.InitDatabase(dbname)) {
                    std::cout << "Unfortunately, I cannot open this database. Could you try again please?\n";
                    continue;
                };

                if (db.CountRows() == 0) {
                    std::cout << "There are no files in database or database doesn't exist. "
                            "Please, try again!\n";
                    continue;
                }

                std::cout << "There are " << db.CountRows() << " files in database." << std::endl;

                std::cout << "Successfully opened database! Beginning patching...\n";
                
                const clock_t begin_time = clock();

                file.PatchAllFilesFromDatabase(db);

                db.CloseDatabase();

                fprintf(stdout, "Spent %f seconds on patching! Thank you for your patience!\n",
                        float(clock() - begin_time) / CLOCKS_PER_SEC);

                std::cout << "Great! File was patched successfully!\n\n";
                break;
            }
        }
    }

    system("pause");
    return 0;
}