//
// Created by Иван_Архипов on 23.11.2017.
//
#include <iostream>
#include <ctime>
#include <algorithm>

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

#include "LotroDat.h"
using namespace LOTRO_DAT;
using namespace std;

int main() {
    std::cout << "Gi1dor's LotRO .dat patcher ver. 5.2.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;

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

        std::cout << "Using .dat file from dat_file_path.txt...\n";
        std::cout << "Opening file " << filename << std::endl;
        DAT_RESULT result = file.InitDatFile(filename, 0);
        if (result >= 2) {
            std::cout << "Dat file may be corrupted! It's opened, but all functions MAY WORK INCORRECTLY! It's better to DOWNLOAD CLEAR .DAT FILE\n";
        }
        if (result <= 0) {
            std::cout << "Dat file path from dat_file_path.txt - " << filename << " may be incorrect (cannot open "
                    "DatFile due to error. See it in errors.log)\n";
            file.CloseDatFile();
        }
    }

    while (file.DatFileState() == CLOSED) {
        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 << "Opening file " << filename << std::endl;

        if (file.InitDatFile(filename, 0) == false) {
                std::cout << "Some error caused while opening the file... "
                        "Could you enter .dat filename once more?" << std::endl;
            file.CloseDatFile();
        }
    }

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

    if (file.CheckIfNotPatched())
        std::cout << "MESSAGE: Dat file is new and haven't been patched yet\n";

    if (file.CheckIfPatchedByOldLauncher())
        std::cout << "MESSAGE: Dat file was patched by old launcher. Capability isn't guaranteed! Some functions may not work properly!!!\n";

    if (file.CheckIfUpdatedByGame())
        std::cout << "MESSAGE: .dat file was updated by game! Need to repair patches with functions RepairPatches() and FinishRepairingPatches()\n";

    std::cout << "Files number: " << file.files_number() << std::endl;

    while (true) {
        std::cout << "Please, choose, what should I do. I can patch datfile from database to .dat file (enter 1), "
                "change locale (enter 2), print current locale (enter 3), enable category (enter 4), disable category (enter 5), "
                "print disabled categories (enter 6), create backup (enter 7), remove backup (enter 8), "
                "restore .dat file from backup (enter 9), check if backup exists (enter 10) or exit (enter -1)\n";

        int cmd = 0;
        std::cout << "Enter number of command (1-10): ";
        std::cin >> cmd;

        std::string tmp;
        std::getline(std::cin, tmp);

        if (cmd == -1) {
            std::cout << "Exiting. Thanks for using me!\n";
            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();
                size_t all = db.CountRows();
                size_t now = 0;

                SubfileData subfile = db.GetNextFile();
                while (!subfile.Empty()) {
                    if (!file.PatchFile(subfile)) {
                        fprintf(stderr, "Error! Caught exception while patching file! Passing it\n");
                    }

                    subfile = db.GetNextFile();
                    ++now;
                    if (now * 100 / all > (now - 1) * 100 / all)
                        std::cout << now * 100 / all << "%\n";
                }

                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;
            }
        }
        if (cmd == 2) {
            std::cout << "Old locale is " << (file.current_locale() == PATCHED ? "RU" : "Original") << endl;
            std::cout << "Changing locale..." << std::endl;
            file.SetLocale(file.current_locale() == PATCHED ? ORIGINAL : PATCHED);
            std::cout << "New locale is " << (file.current_locale() == PATCHED ? "RU" : "Original") << endl << endl;
        }

        if (cmd == 3) {
            std::cout << "Current locale is " << (file.current_locale() == PATCHED ? "RU" : "Original") << endl << endl;
        }

        if (cmd == 4) {
            int category_id = 0;
            std::cout << "Enter category id: ";
            std::cin >> category_id;
            file.EnableCategory(category_id);
            std::cout << "Category successfully enabled!" << std::endl;
        }

        if (cmd == 5) {
            int category_id = 0;
            std::cout << "Enter category id: ";
            std::cin >> category_id;
            file.DisableCategory(category_id);
            std::cout << "Category successfully disabled!" << std::endl;
        }

        if (cmd == 6) {
            std::cout << "Disabled categories: ";
            for (auto i : file.GetInactiveCategoriesList())
                std::cout << i << " ";
            std::cout << endl;
        }

        if (cmd == 7) {
            std::cout << "Creating backup..." << std::endl;
            std::cout << "Create backup function returned " << file.CreateBackup("cli_local_En.backup") << std::endl;
        }

        if (cmd == 8) {
            std::cout << "Removing backup..." << std::endl;
            std::cout << "Remove backup function returned " << file.RemoveBackup("cli_local_En.backup") << std::endl;
        }

        if (cmd == 9) {
            std::cout << "Restoring file from backup..." << std::endl;
            std::cout << "Restore file function returned " << file.RestoreFromBackup("cli_local_En.backup") << std::endl;
        }

        if (cmd == 10) {
            std::cout << "Backup file " << (file.CheckIfBackupExists("clie_local_En.backup") ? "exists!" : "doesn't exist.") << std::endl;
        }
    }
    file.CloseDatFile();

    system("pause");
    return 0;
}

