import json
import logging
from decode_verify_jwt import decode_verify_jwt

class RequestDecorator():

  logger = logging.getLogger(__name__)
  logger.addHandler(logging.NullHandler())
  logger.setLevel(logging.DEBUG)

  def __init__(self, event):
    if not event:
      logger.error("request event not found.")
      raise ValueError

    if "requestContext" in event and "identity" in event["requestContext"]:
      self.__identity_id = None
      self.__username = None
      self.__user_context = None
      self.__path_param = None
      if "cognitoIdentityId" in event["requestContext"]["identity"]:
        self.__identity_id = event["requestContext"]["identity"]["cognitoIdentityId"]
      if "authorizer" in event["requestContext"]:
        self.__username = event["requestContext"]["authorizer"]["claims"]["cognito:username"]
      self.__method = event["requestContext"]["httpMethod"]
      self.__path = event["path"]
      # pathParametersが存在しない場合、Noneになっている
      if event["pathParameters"]:
        self.__path_params = event["pathParameters"]
      else:
        self.__path_params = []
      self.__query = event["queryStringParameters"]
      self.__body = event["body"]
      self.__headers = event["headers"]
      self.__event = event

      if "Authorization" in self.__headers:
        decoded = decode_verify_jwt(self.__headers["Authorization"])
        if decoded:
          self.__user_context = decoded
          self.__identity_id = decoded["cognito:username"]
          self.__username = decoded["preferred_username"]

      self.logger.info("requested http_method: {}".format(self.__method))
      self.logger.info("requested http_headers: {}".format(str(self.__headers)))
      self.logger.info("requested path: {}".format(self.__path))
      self.logger.info("requested path_params: {}".format(self.__path_params))
      self.logger.info("requested query: {}".format(self.__query))
      self.logger.info("requested body: {}".format(str(self.__body)[:500]))
      self.logger.info("requested user_id: {}".format(self.__identity_id))
      self.logger.info("requested user_name: {}".format(self.__username))
      self.logger.info("requested user_context: {}".format(str(self.__user_context)))

    else:
      raise ValueError

  def get_identity_id(self):
    return self.__identity_id

  def get_username(self):
    return self.__username

  def get_method(self):
    return self.__method

  def get_path(self):
    return self.__path

  def get_path_params(self):
    return self.__path_params

  def get_query(self):
    return self.__query

  def get_body(self):
    return json.loads(self.__body)

  def get_headers(self):
    return self.__headers

  def get_raw_event(self):
    return self.__event
