import logging
import os
import unittest
from datetime import datetime
from uuid import UUID

from ecmind_blue_client.ecm import ECM
from ecmind_blue_client.ecm.model import (
    make_document_model,
    make_folder_model,
    make_register_model,
)
from ecmind_blue_client.pool import SyncPoolClient
from ecmind_blue_client.rpc._job_request_file import JobRequestFileFromPath
from tests.models.Unittest_DMS import (
    Unittest_DMS,
    Unittest_DMS_Document,
    Unittest_DMS_Register,
    Unittest_DMS_Subregister,
)
from tests._test_settings import ECM_SERVERS, ECM_USERNAME, ECM_PASSWORD


class TestEcmOrm(unittest.TestCase):
    def setUp(self):
        self.client = SyncPoolClient(servers=ECM_SERVERS, username=ECM_USERNAME, password=ECM_PASSWORD)
        self.ecm = ECM(self.client)
        self.uuid = UUID(bytes=os.urandom(16), version=4)
        self.log = logging.Logger("TestEcmOrm")

    def tearDown(self):
        del self.client

    def test_ecm_orm(self):

        folder = self.ecm.dms.insert_and_get(Unittest_DMS(Name=f"UnitTestFolder_{self.uuid}"))

        register = self.ecm.dms.insert_and_get(
            Unittest_DMS_Register(Name=f"UnitTestRegister_{self.uuid}"),
            folder_id=folder.system.id,
        )

        sub_register = self.ecm.dms.insert_and_get(
            Unittest_DMS_Subregister(Name=f"UnitTestSubRegister_{self.uuid}"),
            folder_id=folder.system.id,
            register_id=register.system.id,
        )

        document = self.ecm.dms.insert_and_get(
            Unittest_DMS_Document(
                OSID=4567,
                Name=f"UnitTestSuberegister_{self.uuid}",
                StringField="Test String",
                DateField=datetime.now().date(),
                DateTimeField=datetime.now(),
                TimeField=datetime.now().time(),
                DoubleField=7.856,
                CheckboxField=True,
                RadioField1=True,
                RadioField2=False,
                TableField=[{"TableCol1": "Val1"}, {"TableCol2": 12345}],
            ),
            folder_id=folder.system.id,
            register_id=sub_register.system.id,
        )

        document = self.ecm.dms.update_and_get(document, files=[JobRequestFileFromPath("README.md")])

        self.ecm.dms.delete(document)
        self.ecm.dms.delete(sub_register)
        self.ecm.dms.delete(register)
        self.ecm.dms.delete(folder)

    def test_ecm_orm_dynamic(self):

        FolderType = make_folder_model("Unittest_DMS")
        RegisterType = make_register_model("Unittest_DMS_Register")
        SubRegisterType = make_register_model("Unittest_DMS_Subregister")
        DocumentType = make_document_model("Unittest_DMS_Document")

        folder = self.ecm.dms.insert_and_get(FolderType(extra_fields={"Name": f"UnitTestFolder_{self.uuid}"}))

        register = self.ecm.dms.insert_and_get(
            RegisterType(extra_fields={"Name": f"UnitTestRegister_{self.uuid}"}),
            folder_id=folder.system.id,
        )

        sub_register = self.ecm.dms.insert_and_get(
            SubRegisterType(extra_fields={"Name": f"UnitTestSubRegister_{self.uuid}"}),
            folder_id=folder.system.id,
            register_id=register.system.id,
        )

        document = self.ecm.dms.insert_and_get(
            DocumentType(
                extra_fields={
                    "Name": f"UnitTestSuberegister_{self.uuid}",
                    "OSID": 4567,
                    "StringField": "Test String",
                    "DateField": datetime.now().date(),
                    "DateTimeField": datetime.now(),
                    "TimeField": datetime.now().time(),
                    "DoubleField": 7.856,
                    "CheckboxField": True,
                    "RadioField1": True,
                    "RadioField2": False,
                },
                extra_table_fields={
                    "TableField": [{"TableCol1": "Val1"}, {"TableCol2": 12345}],
                },
            ),
            folder_id=folder.system.id,
            register_id=sub_register.system.id,
        )

        document = self.ecm.dms.update_and_get(document, files=[JobRequestFileFromPath("README.md")])

        self.ecm.dms.delete(document)
        self.ecm.dms.delete(sub_register)
        self.ecm.dms.delete(register)
        self.ecm.dms.delete(folder)

    def test_ecm_orm_context_switch(self):

        with self.ecm.impersonate("USER_WITH_RIGHTS") as ecm:
            folder = ecm.dms.insert_and_get(Unittest_DMS(Name=f"UnitTestFolder_{self.uuid}"))
            ecm.dms.delete(folder)

        with self.ecm.impersonate("USER_WITHOUT_RIGHTS") as ecm:
            with self.assertRaises(Exception):
                ecm.dms.insert_and_get(Unittest_DMS(Name=f"UnitTestFolder_{self.uuid}"))


if __name__ == "__main__":
    unittest.main()
