import base64
import json

def base64_decode(encoded_str):
    # Add paddings manually if necessary.
    num_missed_paddings = 4 - len(encoded_str) % 4
    if num_missed_paddings != 4:
        encoded_str += b'=' * num_missed_paddings
    return base64.b64decode(encoded_str).decode('utf-8')

class ClaimsHelper:
    def __init__(self, request):
        """User info is the complete header parameter value as generated by the ESP endpoint"""
        claims = request.headers.get('Claims', None)
        print 'Recevied claims: ', claims

        if claims:
            self.claims = json.loads(claims)
        else:
            self.claims = None
            
    def get_user_id(self):
        if claims is not None and 'user_id' in self.claims:
            return self.claims['id']
        else:
            return None

    def is_admin(self, scheme_id=None):
        """Returns true if the claims contain an admin role for the specified scheme"""
        if 'roles' not in self.claims:
            return False

        for role in self.claims['roles']:
            if role['role'] == 'admin' and role['scheme_id'] == scheme_id:
                return True
        
        return False

def create_claims_header(user_id, roles):
    """ Creates a header with custom claims - useful to simulate what will come from FB calls """
    pass