import json

from idcloud.enums.status import Status
from idcloud.resources.connect_verify_document import ConnectVerifyDocumentResource
from idcloud.responses.scenario import Scenario
from idcloud.utils import JSONEncoder


class ConnectVerifyDocumentFaceResource(ConnectVerifyDocumentResource):
    NAME = 'Connect_Verify_Document_Face'

    def face_match(self, scenario_id: str, face: str):
        payload = {
            'name': self.NAME,
            'input': {
                'face': face
            }
        }

        response = self.requestor.request(
            'PATCH', f'/scs/v1/scenarios/{scenario_id}/state/steps/faceMatch',
            payload=payload
        )

        return Scenario(
            id=response.get('id'),
            name=response.get('name'),
            status=Status(response.get('status').lower()),
            steps=response['state'].get('steps'),
            result=response['state'].get('result'),
            raw_request=json.loads(json.dumps(payload, cls=JSONEncoder)),
            raw_response=response
        )


class ConnectVerifyDocumentFacePassiveResource(ConnectVerifyDocumentFaceResource):
    NAME = 'Connect_Verify_Document_Face_Passive_Liveness'


class ConnectVerifyDocumentFaceEnhancedResource(ConnectVerifyDocumentFaceResource):
    NAME = 'Connect_Verify_Document_Face_Enhanced_Liveness'

    def enhanced_liveness(
        self,
        scenario_id: str,
        frames: list,
        client_device_brand: str = None,
        client_device_model: str = None,
        client_os_version: str = None,
        client_version: str = None,
        localization: str = None,
        programming_language_version: str = None
    ):
        meta_data = self._fill_content(
            client_device_brand=client_device_brand,
            client_device_model=client_device_model,
            client_os_version=client_os_version,
            client_version=client_version,
            localization=localization,
            programming_language_version=programming_language_version
        )

        payload = {
            'name': self.NAME,
            'input': {
                'enhancedLiveness': {
                    'video': {
                        'meta_data': meta_data,
                        'workflow_data': {
                            'frames': frames
                        }
                    }
                }
            }
        }

        response = self.requestor.request(
            'PATCH', f'/scs/v1/scenarios/{scenario_id}/state/steps/enhancedLiveness',
            payload=payload
        )

        return Scenario(
            id=response.get('id'),
            name=response.get('name'),
            status=Status(response.get('status').lower()),
            steps=response['state'].get('steps'),
            result=response['state'].get('result'),
            raw_request=json.loads(json.dumps(payload, cls=JSONEncoder)),
            raw_response=response
        )
