from imc.auth import Auth
import config
from asyncdb import AsyncDB

class TOJAuth(Auth):
    ACCESS_READ     = 0x1
    ACCESS_WRITE    = 0x2
    ACCESS_CREATE   = 0x4
    ACCESS_DELETE   = 0x8
    ACCESS_SETPER   = 0x10
    ACCESS_EXECUTE  = 0x20

    ACCESS_ALL      = -1

    ROLETYPE_USER   = 1
    ROLETYPE_3RD    = 2
    ROLETYPE_MOD    = 3
    ROLETYPE_TOJ    = 4
    ROLETYPE_GROUP  = 5
    ROLETYPE_GUEST  = 6

    ROLEID_TOJ      = 1
    ROLEID_MOD      = 2
    ROLEID_GUEST    = 99

    ROLEID_SQUARE_ADMIN_GROUP   = 101
    ROLEID_PROBLEM_ADMIN_GROUP  = 102

    ROLEID_USER_GROUP   = 201

    _accessid = 1

    def __init__(self, pubkey, privkey = None):
        super().__init__()

        self.set_verifykey(pubkey)
        if privkey != None:
            self.set_signkey(privkey)

        TOJAuth.instance = self
        TOJAuth.db = AsyncDB(config.CORE_DBNAME, config.CORE_DBUSER,
                config.CORE_DBPASSWORD)

    def create_iden(self, link, idenid, roletype, payload = {}):
        iden = payload
        iden.update({
            'link' : link,
            'idenid' : idenid,
            'roletype' : roletype
        })

        return self.sign_iden(iden)

    def verify_iden(self, conn_link, idendesc):
        iden = self.get_iden(idendesc) 
        if iden == None:
            return False

        if conn_link != iden['link']:
            return False

        return True
    
    @staticmethod
    def check_access(accessid, access_mask):
        def wrapper(f):