from snek.system import security
from snek.system.service import BaseService


class UserService(BaseService):
    mapper_name = "user"
    
    async def search(self, query, **kwargs):
        query = query.strip().lower()
        if not query:
            raise []
        results = []
        async for result in self.find(username=dict(ilike='%' + query + '%'), **kwargs):
            results.append(result)
        return results

    async def validate_login(self, username, password):
        model = await self.get(username=username)
        if not model:
            return False
        if not await security.verify(password, model["password"]):
            return False
        return True

    async def save(self, user):
        if not user['color']:
            user['color'] = await self.services.util.random_light_hex_color()
        return await super().save(user)


    async def register(self, email, username, password):
        if await self.exists(username=username):
            raise Exception("User already exists.")
        model = await self.new()
        model["nick"] = username
        model['color'] = await self.services.util.random_light_hex_color()
        model.email.value = email
        model.username.value = username
        model.password.value = await security.hash(password)
        if await self.save(model):
            if model:
                channel = await self.services.channel.ensure_public_channel(
                    model["uid"]
                )
                if not channel:
                    raise Exception("Failed to create public channel.")
            return model
        raise Exception(f"Failed to create user: {model.errors}.")
