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"""
        encoded_info = request.headers.get('X-Endpoint-API-UserInfo', None)
        claims = request.headers.get('Claims', None)

        import pdb; pdb.set_trace()
        

        print 'Claims: ', claims

        if encoded_info:
            info_json = base64_decode(encoded_info)
            self.user_info = json.loads(info_json)
        else:
            self.user_info = {'id': 'anonymous'}
            
        self.log_header()

    def get_user_id(self):
        if 'id' in self.user_info:
            return self.user_info['id']

        return None

    def is_admin(self, scheme_id=None):
        """Returns true if the claims contain an admin role for the specified scheme"""
        return True

        if 'custom_claims' not in self.user_info:
            return False

        if 'roles' not in self.user_info['custom_claims']:
            return False

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

    def log_header(self):
        print 'X-Endpoint-API-UserInfo: ', self.user_info

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