"""
Originally written for CUYC 
Philip Sargent (Feb.2021)

Modified for Expo April 2021.

To run just these, do 
uv run  manage.py test -v 3 troggle.core.TESTS.test_logins
"""

import pathlib
import re
from http import HTTPStatus

from django.contrib.auth.models import User
from django.test import Client, TestCase

import troggle.settings as settings
from troggle.core.models.troggle import Expedition
from troggle.core.models.wallets import Wallet
from troggle.core.utils import current_expo

current_year = current_expo()


def create_user(name=None, last_name="Caver", is_superuser=False):
    u = User()
    u.username = name
    u.email = f"philip.sargent+{name}@gmail.com"
    u.first_name, u.last_name = name, last_name
    u.set_password("secretword") # all test users have same password
    u.save()
    return u
    

class DataTests(TestCase):
    """These check that the NULL and NON-UNIQUE constraints are working in the database
    
    no tests here... !"""

    @classmethod
    def setUpTestData(cls):
        pass

    def setUp(self):
        create_user(name="expo")
 
    def tearDown(self):
        Users.objects.all().delete()


class LoginTests(TestCase):

    def setUp(self):
        create_user(name="expo")
        create_user(name="expotest")
        create_user(name="expotestadmin",  is_superuser = True)

    def tearDown(self):
        User.objects.all().delete()

    def test_fix_admin_login_fail(self):
        c = self.client
        u = User.objects.get(username="expotest")

 
        response = c.get("/admin/")
        content = response.content.decode()
        # with open('admin-op.html', 'w') as f:
        # f.write(content)
        t = re.search(r"Troggle administration", content)
        self.assertIsNone(t, "Logged in as '" + u.username + "' (not staff) but still managed to get the Admin page")


class PostTests(TestCase):
    """Tests walletedit form"""

    @classmethod
    def setUpTestData(cls):
        pass

    def setUp(self):
        create_user(name="expo")
        create_user(name="expotestadmin",  is_superuser = True)
        self.user = create_user(name="expotest")
        
        c = self.client

        testyear = "2022"
        wname = f"{testyear}:00"
        self.testyear = testyear
        w = Wallet()
        w.pk = 9100
        w.fpath = str(pathlib.Path(settings.SCANS_ROOT, wname))
        w.walletname = wname
        w.save()
        self.wallet = w

        e = Expedition()
        e.year = testyear
        e.save()
        self.expedition = e

    def tearDown(self):
        User.objects.all().delete()
        Wallet.objects.all().delete()
        Expedition.objects.all().delete()

    def test_file_permissions(self):
        """Expect to be allowed to write to SCANS_ROOT, DRAWINGS_DATA, SURVEX_DATA, EXPOWEB
        Need to login first.
        """
        c = self.client
        u = self.user
        testyear = self.testyear

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        for p in [settings.SCANS_ROOT, 
                settings.DRAWINGS_DATA / "walletjson", 
                settings.EXPOWEB / "documents", 
                settings.SURVEX_DATA / "docs"
                ]:
            
            _test_file_path = pathlib.Path(p, "_created_by_test_suite.txt")
            self.assertEqual(_test_file_path.is_file(), False)

            with open(_test_file_path, "w") as f:
                f.write("test string: can we write to this directory?")
            self.assertEqual(_test_file_path.is_file(), True)
            _test_file_path.unlink()
                
    def test_scan_upload(self):
        """Expect scan upload to wallet to work on any file
        Need to login first.

        This upload form looks for the Cave and the Wallet, so the test fails if the database is not loaded with the cave
        identified in the wallet
        """
        c = self.client
        from django.contrib.auth.models import User

        u = User.objects.get(username="expotest")
        testyear = self.testyear

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        with open("core/fixtures/test_upload_file.txt", "r") as testf:
            response = self.client.post(
                f"/walletedit/{testyear}:00", data={"name": "test_upload_file.txt", "uploadfiles": testf, "who_are_you": "Gumby <gumby@tent.expo>"}
            )
            content = response.content.decode()
            self.assertEqual(response.status_code, HTTPStatus.OK)
            # with open('_test_response__scan_upload.html', 'w') as f:
                # f.write(content)
            for ph in [
                r"test_upload_",
                rf"&larr; {testyear}#00 &rarr;",
                r"description written",
                r"Plan not required",
                r"edit settings or upload a file",
            ]:
                phmatch = re.search(ph, content)
                self.assertIsNotNone(phmatch, "Failed to find expected text: '" + ph + "'")

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        remove_file = pathlib.Path(settings.SCANS_ROOT) / f'{testyear}' / f'{testyear}#00'/ 'test_upload_file.txt'
        remove_file.unlink()
        
        # Just uploading a file does NOT do any git commit.
        # You need to create or edit a contents.json file for that to happen.

    def test_photo_upload(self):
        """Expect photo upload to work on any file (contrary to msg on screen)
        Upload into current default year. 
        Deletes file afterwards
        Need to login first.
        """
        c = self.client
        u = self.user

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        with open("core/fixtures/test_upload_file.txt", "r") as testf:
            response = self.client.post(
                "/photoupload", data={"name": "test_upload_file.txt", "renameto": "", "uploadfiles": testf}
            )
            content = response.content.decode()
            self.assertEqual(response.status_code, HTTPStatus.OK)
            self.assertEqual(response.status_code, HTTPStatus.OK)
            # with open('_test_response_photo_upload.html', 'w') as f:
                # f.write(content)
            for ph in [
                r"test_upload_",
                r"Upload photos into /photos/" + str(current_year),
                r" you can create a new folder in your name",
                r"Create new Photographer folder",
                r"only photo image files are accepted",
            ]:
                phmatch = re.search(ph, content)
                self.assertIsNotNone(phmatch, "Failed to find expected text: '" + ph + "'")

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        remove_file = pathlib.Path(settings.PHOTOS_ROOT, current_year) / "test_upload_file.txt"
        remove_file.unlink()

    def test_photo_upload_rename(self):
        """Expect photo upload to work on any file (contrary to msg on screen)
        Upload into current default year. 
        Deletes file afterwards
        Need to login first.
        """
        c = self.client
        u = self.user

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        rename = "RENAMED-FILE.JPG"
        with open("core/fixtures/test_upload_file.txt", "r") as testf:
            response = self.client.post(
                "/photoupload", data={"name": "test_upload_file.txt", "renameto": rename, "uploadfiles": testf}
            )
            content = response.content.decode()
            self.assertEqual(response.status_code, HTTPStatus.OK)
            self.assertEqual(response.status_code, HTTPStatus.OK)
            # with open('_test_response.html', 'w') as f:
            # f.write(content)
            for ph in [rename]:
                phmatch = re.search(ph, content)
                self.assertIsNotNone(phmatch, "Failed to find expected text: '" + ph + "'")

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        remove_file = pathlib.Path(settings.PHOTOS_ROOT, current_year) / rename
        if remove_file.is_file():
            remove_file.unlink()
        
        

    def test_photo_folder_create(self):
        """Create folder for new user
        Create in current year.
        Deletes folder afterwards
        Need to login first.
        """
        c = self.client
        u = self.user

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        response = self.client.post("/photoupload", data={"photographer": "GussieFinkNottle"})
        content = response.content.decode()
        self.assertEqual(response.status_code, HTTPStatus.OK)
        # with open('_test_response.html', 'w') as f:
            # f.write(content)
        for ph in [r"Create new Photographer folder", r"/GussieFinkNottle/"]:
            phmatch = re.search(ph, content)
            self.assertIsNotNone(phmatch, "Failed to find expected text: '" + ph + "'")

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        remove_dir = pathlib.Path(settings.PHOTOS_ROOT, current_year) / "GussieFinkNottle"
        if remove_dir.is_dir():
            print(f"{remove_dir} was created, now removing it.")
            remove_dir.rmdir()

    def test_dwg_upload_txt(self):
        """Expect .pdf file to be refused upload
        Need to login first.
        """
        c = self.client
        u = self.user


        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        with open("core/fixtures/test_upload_file.pdf", "r") as testf:
            response = self.client.post(
                "/dwgupload/uploads", data={"name": "test_upload_file.txt", "uploadfiles": testf, "who_are_you": "Gumby <gumby@tent.expo>"}
            )
            content = response.content.decode()
            # with open('_test_response_dwg_upload_txt.html', 'w') as f:
                # f.write(content)            
            self.assertEqual(response.status_code, HTTPStatus.OK)
            t = re.search("Files refused:", content)
            self.assertIsNotNone(t, 'Logged in but failed to see "Files refused:"')


    def test_dwg_upload_drawing(self):
        """Expect no-suffix file to upload
        Note that this skips the git commit process. That would need a new test.
        Need to login first.
        """
        c = self.client
        u = self.user


        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")
        c.login(username=u.username, password="secretword")

        with open("core/fixtures/test_upload_nosuffix", "r") as testf:
            response = self.client.post(
                "/dwguploadnogit/uploads", data={"name": "test_upload_nosuffix", "uploadfiles": testf, "who_are_you": "Gumby <gumby@tent.expo>"}
            )
            content = response.content.decode()
            # with open('_test_response_dwg_upload_drawing.html', 'w') as f:
                # f.write(content)
            self.assertEqual(response.status_code, HTTPStatus.OK)
            for ph in [
                r"test_upload_nosuffix",
                r"You cannot create folders here",
                r"Creating a folder is done by a nerd",
            ]:
                phmatch = re.search(ph, content)
                self.assertIsNotNone(
                    phmatch, "Expect no-suffix file to upload OK. Failed to find expected text: '" + ph + "'"
                )

        # Does not use the filename Django actually uses, assumes it is unchanged.  Bug: accumulates one file with random name 
        # added each time it is run. The name of the uploaded file is only available within the code where it happens 
        # UploadedFile.name see https://docs.djangoproject.com/en/4.1/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile
        remove_file = pathlib.Path(settings.DRAWINGS_DATA) / "uploads" / "test_upload_nosuffix"
        if remove_file.is_file():
            remove_file.unlink()


class ComplexLoginTests(TestCase):
    """These test the login and capabilities of logged-in users, they do not use fixtures"""

    def setUp(self):
        """setUp runs once for each test in this class"""
        create_user(name="expo")
        create_user(name="expotest")
        create_user(name="expotestadmin",  is_superuser = True)

    def tearDown(self):
        self.client.logout()  # not needed as each test creates a new self.client
        User.objects.all().delete()


    # def test_login_redirect_for_non_logged_on_user(self): # need to fix this in real system
    # c = self.client
    # # Need to login first. Tests that we are redirected to login page if not logged in
    # response = c.get('noinfo/cave-number-index')
    # self.assertRedirects(response, "/login/?next=/committee/appointments/")

    def test_ordinary_login(self):
        c = self.client
        u = User.objects.get(username="expotest")

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")

        logged_in = c.login(username=u.username, password="secretword")  
        self.assertTrue(logged_in, "FAILED to login as '" + u.username + "'")

        response = c.get("/accounts/login/")  # defined by auth system
        content = response.content.decode()
        t = re.search(r"You are now logged in", content)
        self.assertIsNotNone(t, "Logged in as '" + u.username + "' but failed to get 'Now you can' greeting")

    def test_authentication_login(self):
        c = self.client
        u = User.objects.get(username="expotest")

        self.assertTrue(u.is_active, "User '" + u.username + "' is INACTIVE")

        # This is weird. I thought that the user had to login before she was in the authenticated state
        self.assertTrue(u.is_authenticated, "User '" + u.username + "' is NOT AUTHENTICATED before login")

        logged_in = c.login(username=u.username, password="secretword")  
        self.assertTrue(logged_in, "FAILED to login as '" + u.username + "'")

        self.assertTrue(u.is_authenticated, "User '" + u.username + "' is NOT AUTHENTICATED after login")

        # c.logout() # This next test always means user is still authenticated after logout. Surely not?
        # self.assertFalse(u.is_authenticated, 'User \'' + u.username + '\' is STILL AUTHENTICATED after logout')

    def test_admin_login(self):
        c = self.client
        u = User.objects.get(username="expotestadmin")

        logged_in = c.login(username=u.username, password="secretword")  
        self.assertTrue(logged_in, "FAILED to login as '" + u.username + "'")

        response = c.get("/admin/login/")
        content = response.content.decode()
        # fn='admin-op.html'
        # print(f"Writing {fn}")
        # with open(fn, 'w') as f:
            # f.write(content)
        t = re.search(r"Troggle database administration", content)
        self.assertIsNotNone(t, "Logged in as '" + u.username + "' but failed to get the Troggle Admin page")

    def test_noinfo_login(self):

        c = self.client  # inherited from TestCase
        u = User.objects.get(username="expotest")

        logged_in = c.login(username=u.username, password="secretword")  
        self.assertTrue(logged_in, "FAILED to login as '" + u.username + "'")
        response = c.get("/stats")  # a page with the Troggle menus
        content = response.content.decode()
        t = re.search(r"User\:expotest", content)
        self.assertIsNotNone(t, "Logged in as '" + u.username + "' but failed to get 'User:expotest' heading")

        response = c.get("/noinfo/cave-number-index")
        content = response.content.decode()
        t = re.search(r"2001-07 Hoffnungschacht", content)
        self.assertIsNotNone(t, "Logged in as '" + u.username + "' but failed to get /noinfo/ content")

    def test_user_force(self):

        c = self.client
        u = User.objects.get(username="expotest")

        try:
            c.force_login(u)
        except:
            self.assertIsNotNone(
                None,
                "Unexpected exception trying to force_login as '"
                + u.username
                + "' but failed (Bad Django documentation?)",
            )

        response = c.get("/stats")  # a page with the Troggle menus
        content = response.content.decode()
        t = re.search(r"Log out", content)
        self.assertIsNotNone(t, "Forced logged in as '" + u.username + "' but failed to get Log out heading")

        response = c.get("/accounts/login/")
        content = response.content.decode()
        t = re.search(r"You are now logged in", content)
        self.assertIsNotNone(t, "Forced logged in as '" + u.username + "' but failed to get /accounts/profile/ content")
