'Parse a link filter expression and convert it into an
S3ResourceQuery that can be added to the search_ac resource.
Link filter expressions are used to exclude records from
the (autocomplete-)search that are already linked to the master
record.
General format:
?link=<linktablename>.<leftkey>.<id>.<rkey>.<fkey>
Example:
?link=project_organisation.organisation_id.5.project_id.id
@param expression: the link filter expression'

@staticmethod
def link_filter(table, expression):

    try:
        (link, lkey, _id, rkey, fkey) = expression.split('.')
    except ValueError:
        return None
    linktable = current.s3db.table(link)
    if linktable:
        fq = ((linktable[rkey] == table[fkey]) & (linktable[lkey] == _id))
        if ('deleted' in linktable):
            fq &= (linktable.deleted != True)
        linked = current.db(fq).select(table._id)
        from s3query import FS
        pkey = FS('id')
        exclude = (~ pkey.belongs([r[table._id.name] for r in linked]))
        return exclude
    return None
