import os
import json
import sys
import uuid
import random
from datetime import datetime, timezone
import logging
from faker import Faker
from scim2_models import User, Group
logging.StreamHandler(sys.stdout)
logger = logging.getLogger(__name__)

faker = Faker()

def make_groups(count=10):

    for x in range(count):
        TMP_USERS_LIST = USERS[:]
        group_id = f'{uuid.uuid4()}'
        group_name = faker.catch_phrase()
        group_payload = {
          "id": group_id,
          "externalID": group_id,
          "meta":  {
            "created":"2013-04-16T09:10:45Z",
            # "modified":"2013-04-16T09:10:45Z"
          },
          "displayName": group_name,
          "members":  [ ],
          # "members":  {
          #   'totalResults': 100,
          #   'startSubIndex': 1,
          #   'subCount': 5,
          #   'Resources': [

          #   ],
          # },
          "schemas":  [
            "urn:scim:schemas:core:2.0:group"
          ]

        }

        '''
        for x in range(random.randint(0, len(USERS))):
            u = TMP_USERS_LIST.pop(random.choice(list(range(0,
                                                            len(TMP_USERS_LIST)))))
            user_obj = {
              "value": u['id'],
              "display": u['displayName']
            } 
            # group_payload['members']['Resources'].append(user_obj)
            group_payload['members'].append(user_obj)
        '''

        group = Group.model_validate(group_payload)
        # assert user.user_name == 'bjensen@example.com'
        # assert user.meta.created == datetime.datetime(
        #     2010, 1, 23, 4, 56, 22, tzinfo=datetime.timezone.utc
        # )
        yield group.model_dump()


def make_users(count=10):
    for x in range(count):
        logger.info(f'creating another user: {x}')
        profile = faker.profile()
        first_name = faker.first_name()
        last_name = faker.last_name() 
        profile['name'] = f'{first_name} {last_name}'
        domain = 'acme.com'
        username = f'{first_name}.{last_name}'
        # created = '2025-02-16 13:38:26'
        created = datetime.now(timezone.utc)
        user_id = f'{uuid.uuid4()}'
        user_payload = {
            'schemas': [
                'urn:ietf:params:scim:schemas:core:2.0:User',
                # 'urn:ietf:params:scim:schemas:core:2.0:Extended',
                ],
            'id': user_id,
            'userName': f'{username}@{domain}',
            'name': {
                'familyName': last_name,
                'givenName': first_name
            },
            # 'lastName': last_name,
            'display_name': f'{first_name} {last_name}',
            'active': True,
            'userName': username,
            "emails": [
                {"value": f"{username}@example.com", "type": "home"},
                {"value": f"{username}@example.com", "type": "work"},
                {"value": f"{username}@test.org", "type": "other"}
            ],
            # 'mailAlias': '',
            # 'mailServer': 'null',
            # 'firstName': first_name,
            # 'createdDate': created,
            # 'multiSession': False,
            # 'createdByUser': 'hrms',
            # 'modifiedByUser': 'admin',

            # 'schemas': [
            #     'urn:soffid:com.soffid.iam.api.User'
            # ],
            # 'modifiedDate': '2021-05-04 09:24:54',
            # 'attributes': {},
            'userType': 'I',
            # 'homeServer': 'null',
            # 'primaryGroupDescription': 'World Original',
            # 'primaryGroup': 'world',
            'meta': {
                'resourceType': 'User', 'created': created,
                'lastModified': '2011-05-13T04:42:34Z',
                'version': '3694e05e9dff590',
                'location': f'http://flask2:8080/v2/Users/{user_id}',
                # 'links': {
                #     'roleAccounts': f'http://flask2:8080/scim2/v2/appname/RoleAccount?user_id={user_id}&enabled=true',
                #     'groupUsers': f'http://flask2:8080/scim2/v2/appname/GroupUser?user_id={user_id}&enabled=true',
                #     'accounts': f'http://flask2:8080/scim2/v2/appname/Account?user_id={user_id}&enabled=true',
                # },
            },
        }

        user = User.model_validate(user_payload)
        # assert user.user_name == 'bjensen@example.com'
        # assert user.meta.created == datetime.datetime(
        #     2010, 1, 23, 4, 56, 22, tzinfo=datetime.timezone.utc
        # )
        yield user.model_dump()

users_filename = '/app/test-users2.db.json'
groups_filename = '/app/test-groups2.db.json'

if os.path.exists(users_filename):
    with open(users_filename) as _f:
        USERS = json.load(_f)
else:
    USERS = list(make_users(500))
    with open(users_filename, 'w+') as _f:
        json.dump(USERS, _f)

if os.path.exists(groups_filename):
    with open(groups_filename) as _f:
        GROUPS = json.load(_f)
else:
    GROUPS = list(make_groups(20))
    with open(groups_filename, 'w+') as _f:
        json.dump(GROUPS, _f)

logger.info('There are %s users in the DB', len(USERS))
# exit()
USERS_DB = {u['id']:u for u in USERS}

logger.info('There are %s groups in the DB', len(GROUPS))
# exit()
GROUPS_DB = {g['id']:g for g in GROUPS}
