#!/usr/bin/env python3
# encoding: utf-8
#
# ** header v3.0
# This file is a part of the CaosDB Project.
#
# Copyright (C) 2022 Indiscale GmbH <info@indiscale.com>
# Copyright (C) 2022 Henrik tom Wörden <h.tomwoerden@indiscale.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ** end header
#


import os
import re
from tempfile import NamedTemporaryFile
import unittest

from caosadvancedtools.loadFiles import compile_file_list, create_re_for_file_list, combine_ignore_files

BASEDIR = os.path.dirname(os.path.realpath(__file__))


class Caosdbignore(unittest.TestCase):
    def setUp(self):
        pass

    def test_compile(self):
        files = compile_file_list(os.path.join(BASEDIR, "caosdbignore-example"),
                                  os.path.join(BASEDIR, "data"))
        assert len(files) == 3
        assert os.path.join(BASEDIR, "data", "datatypes.xlsx") in files
        assert os.path.join(BASEDIR, "data", "README.xlsx") in files
        assert os.path.join(BASEDIR, "data", "Publications/Posters/2019-02-03_something/README.md") in files

    def test_regex(self):
        files = [r"/dies/ist/simple", r"/dies/eh(er)/nich?t"]
        regex = create_re_for_file_list(files, "/dies", "/dies")
        assert re.match(regex, files[0]) is not None
        assert re.match(regex, files[1]) is not None
        assert re.match(regex, "/dies/ist") is not None
        assert re.match(regex, "/die") is None
        assert re.match(regex, files[0]+files[1]) is None
        assert re.match(regex, "d") is None

    def test_combine(self):
        fi1 = NamedTemporaryFile(delete=False, mode="w")
        fi1.write("ha")
        fi1.close()
        fi2 = NamedTemporaryFile(delete=False, mode="w")
        fi2.write("ha")
        fi2.close()
        fi_new = combine_ignore_files(fi1.name, fi2.name)
        with open(fi_new, "r") as fi:
            assert "haha" == fi.read()
