"""tests for file_lib"""
import glob
import os
import logging
import unittest

from pathlib import Path

from amilib.file_lib import FileLib
from amilib.util import Util

from test.resources import Resources
from test.test_all import AmiAnyTest

FILE_LIB = "file_lib"
PDF_LIB = "pdf_lib"
TEXT_LIB = "text_lib"
_SETUP = "_setup"
_TEARDOWN = "_teardown"
TEST = "test"

"""
a few tests on globbing, etc"""

logger = Util.get_logger(__name__)

class File0Test(AmiAnyTest):
    # nothing much here
    logger = logging.getLogger("test_file")
    TEST = "test"

    OPTIONS = [
        FILE_LIB,
        PDF_LIB,
        TEXT_LIB,
        _SETUP,
        _TEARDOWN,
    ]

    @classmethod
    def example_setup(cls, pyamix):
        """ setup test or examples
        these are general commands (i.e. not subcommands)
        :pyamix:
        """
        pyamix.run_commands([
            "--delete ${exam_temp}",
            "--copy ${examples_test.p} ${exam_temp} overwrite",
        ])

    @classmethod
    def example_teardown(cls, pyamix):
        """ clean example files

        """
        pyamix.run_command([
            "--delete", "${exam_temp}",
        ])

    @classmethod
    def run_arg_tests(cls, args):
        """This needs revision , maybe using Examples()"""
        cls.logger.warning(f"*****running tests : {args[TEST]}")
        if not args[TEST]:
            cls.logger.warning(f"No tests given: choose some/all of {TEST}")
            return
        if FILE_LIB in args[TEST]:
            cls.logger.warning("run test_file")
            cls.test_file.main()
        if PDF_LIB in args[TEST]:
            cls.logger.warning("run test_pdf")
            cls.test_pdf.test_read_pdf()
        if TEXT_LIB in args[TEST]:
            cls.logger.warning("run test_text NYI")


    @unittest.skip("if not windows")
    def test_glob_with_windows_FILE(self):
        """
        some instances of glob.glob with fully forward slashes generate backslash or double backslash on windows
        """
        input_dir = Path(Resources.TEST_RESOURCES_DIR, "ar6", "cleaned_content")
        assert input_dir.exists()
        glob_str = f"{str(input_dir)}/**/html_with_ids.html"
        files = FileLib.posix_glob(glob_str, recursive=True)
        assert len(files) > 70
        for file in files[:5]:
            logger.debug(f"file: {file}")
            assert not "\\" in file # backslash is not generated by UNIX/MacOS
            assert "/" in file


    @classmethod
    @unittest.skip("not yet right")
    def test_expand_braces(cls):
        """
        no longer tests braces
        :return:
        """

        home = os.path.expanduser("~")
        file = __file__
        python_dir = os.path.abspath(file + "/../")
        resources_dir = os.path.join(python_dir, "resources")
        logger.debug("python", os.path.abspath(python_dir))
        physchem_dir = os.path.abspath(python_dir + "/../")
        open_diagram = os.path.abspath(physchem_dir + "/../")
        logger.debug(os.path.abspath(open_diagram))
        opend = os.path.join(open_diagram, "*")
        logger.debug("opend", opend)
        logger.debug(f"od0 {glob.glob(opend)}")
        open_diagram01 = os.path.join(physchem_dir, "**", "liion10", "**", "*.*ml")
        logger.debug(f"od01 {glob.glob(open_diagram01)}")

        # open_diagram02 = os.path.join(home, "projects", "*iagram", "{*ot*,*.md}")
        # logger.debug("od02", bg.braced_glob(open_diagram02))
        open_diagram11 = os.path.join(home, "projects", "*iagram", "*", "*", "*.xml")
        logger.debug("od", open_diagram11)
        logger.debug("b", glob.glob(open_diagram11))
        open_diagram12 = os.path.join(home, "projects", "*iagram", "**", "*.xml")
        logger.debug("od", open_diagram12)

    def test_get_input_strings(self):
        """
        reads lists of words with optional split
        """
        words = FileLib.get_input_strings("foo")
        assert words == ["foo"]
        words = FileLib.get_input_strings(["foo"])
        assert words == ["foo"]
        words = FileLib.get_input_strings(["foo", "bar"])
        assert words == ["foo", "bar"]
        words = FileLib.get_input_strings("foo bar")
        assert words == ["foo bar"]
        words = FileLib.get_input_strings("foo bar", split=True)
        assert words == ["foo", "bar"]

    def test_get_input_strings_from_file(self):
        """
        reads lists of words in file/s
        """
        words = FileLib.get_input_strings(Path(Resources.TEST_RESOURCES_DIR, "wordlists", "small_2.txt"))
        assert words == ["anthropogenic", "tropospheric"]
        words = FileLib.get_input_strings(Path(Resources.TEST_RESOURCES_DIR, "wordlists", "small_10.txt"))
        assert words == [
            'anthropogenic', 'physical-biogeochemical', 'peat drainage', 'tropospheric', 'permafrost',
            'centennial', 'aerosols', 'sequestration', 'albedo', 'exacerbating'
        ]
        words = FileLib.get_input_strings(Path(Resources.TEST_RESOURCES_DIR, "wordlists", "small_10.txt"), split=True)
        # assert words == [
        #     'anthropogenic', 'physical-biogeochemical', 'peat', 'drainage', 'tropospheric', 'permafrost',
        #     'centennial', 'aerosols', 'sequestration', 'albedo', 'exacerbating'
        # ]
        assert words ==['anthropogenic',
 'physical-biogeochemical',
 'peat',
 'drainage',
 'tropospheric',
 'permafrost',
 'centennial',
 'aerosols',
 'sequestration',
 'albedo',
 'exacerbating']
        # list of files
        words = FileLib.get_input_strings([
            Path(Resources.TEST_RESOURCES_DIR, "wordlists", "small_5.txt"),
            Path(Resources.TEST_RESOURCES_DIR, "wordlists", "small_10.txt")])

        # assert words == ['anthropogenic', 'physical-biogeochemical', 'peat drainage', 'tropospheric',
        #     'permafrost', 'centennial', 'aerosols', 'sequestration', 'albedo', 'exacerbating']
        assert words == ['anthropogenic',
 'tropospheric',
 'permafrost',
 'sequestration',
 'albedo',
 'anthropogenic',
 'physical-biogeochemical',
 'peat drainage',
 'tropospheric',
 'permafrost',
 'centennial',
 'aerosols',
 'sequestration',
 'albedo',
 'exacerbating']

        # list of files
        words = FileLib.get_input_strings([
            Path(Resources.TEST_RESOURCES_DIR, "wordlists", "small_5.txt"),
            Path(Resources.TEST_RESOURCES_DIR, "wordlists", "small_10.txt")], split=True)

        assert words == ['anthropogenic',
 'tropospheric',
 'permafrost',
 'sequestration',
 'albedo',
 'anthropogenic',
 'physical-biogeochemical',
 'peat',
 'drainage',
 'tropospheric',
 'permafrost',
 'centennial',
 'aerosols',
 'sequestration',
 'albedo',
 'exacerbating']




def main():
    File0Test.test_file_simple()
    File0Test.test_templates()
