"""FormEncode validators."""

import formencode

from floof.model.users import User, UserRelationshipTypes

class UniqueExistingRow(formencode.FancyValidator):
    """Given a column object, converts a unique value from that column into the
    corresponding row object.
    """
    def __init__(self, table, column):
        self.table = table
        self.column = column
        super(formencode.FancyValidator, self).__init__()

    def _to_python(self, value, state):
        try:
            row = self.table.query.filter(self.column == value).one()
        except BaseException, e:
            raise formencode.Invalid(
                'No unique row.',
                value, state
            )
        return row

### user_settings

class UserRelationshipToggleForm(formencode.Schema):
    target_user = UniqueExistingRow(User, User.id)
    type = formencode.compound.Pipe(
        formencode.validators.Int(),
        formencode.validators.OneOf(
            [v for (k, v) in UserRelationshipTypes.__dict__.items()
                if k[0] != '_']
        ),
    )
    add_remove = formencode.validators.OneOf([u'add', u'remove'])
