# file_widget_fastreload.py
# Copyright 2023 Roger Marsh
# Licence: See LICENCE (BSD licence)

"""Try fast load of a ChessTab database from fast unload output.

Purpose is to verify fast load functions correctly for at least one set
of 'TAPE' files: in particular a set generated by fast unload.

The attempt to write a fast load input files generator for PGN files from
the description of file formats in DPT DBA Guide failed: so see if there
is a way fast load works and copy that.
"""

import tkinter
import os
import time

import tkinter.messagebox
import tkinter.filedialog

import dptdb.dptapi

from solentware_base.core.constants import DPT_SYSFL_FOLDER

from ..dpt import chessdpt


def file_fastreload(dbpath, inputdir):
    """Open database, fast load Games file, and close database."""
    print(time.ctime())
    cdb = ChessDatabase(dbpath, allowcreate=True)
    cdb.open_database()
    for table in cdb.table.values():
        # Load accepts positional arguments only.
        # Want 'dir' argument as 'dbpath', not the default '#FASTIO' via
        # definition of FUNLOAD_DIR.
        # So have to specify options where FLOAD_DEFAULT is the default
        # option.
        table.opencontext.Load(dptdb.dptapi.FLOAD_DEFAULT, 0, None, inputdir)
    cdb.close_database()
    print(time.ctime())


class ChessDatabase(chessdpt.ChessDatabase):
    """Provide access to a database of games of chess."""

    def __init__(self, databasefolder, sysfolder=None, **kargs):
        """Extend to override default sysfolder."""
        if databasefolder:
            databasefolder = os.path.abspath(databasefolder)
            if sysfolder is None:
                sysfolder = os.path.join(databasefolder, DPT_SYSFL_FOLDER)
        super().__init__(databasefolder, sysfolder=sysfolder, **kargs)

    # Set default parameters for fastload as deferred update alternative.
    def create_default_parms(self):
        """Create default parms.ini file for fastload without transactions.

        This means transactions are disabled and a small number of DPT
        buffers.

        """
        if not os.path.exists(self.parms):
            parms = open(self.parms, "w")
            try:
                parms.write("RCVOPT=X'00' " + os.linesep)
                parms.write("MAXBUF=100 " + os.linesep)
            finally:
                parms.close()


class FileWidget:
    """Select ChessTab database to fast reload from fast unload output."""

    def __init__(self):
        """Import games into database using engine_name database engine."""
        root = tkinter.Tk()
        root.wm_title("Fast Reload ChessTab Database")
        root.wm_iconify()
        dbdir = tkinter.filedialog.askdirectory(
            title="Fast Reload ChessTab Database"
        )
        if dbdir:
            inputdir = tkinter.filedialog.askdirectory(
                title="Fast Reload Input Directory"
            )
            if inputdir:
                if tkinter.messagebox.askyesno(
                    title="Fast Reload Games",
                    message="Proceed with Fast Reload",
                ):
                    file_fastreload(dbdir, inputdir)
        root.destroy()


if __name__ == "__main__":
    FileWidget()
