#!/usr/bin/python

import logging, logging.handlers
import hmac, hashlib, uuid
import time, sys
import argparse, getpass, json
import urllib.request

log = logging.getLogger(__name__)

if __name__ == '__main__':
  logger = logging.getLogger()
  logger.setLevel(logging.INFO)
  formatter = logging.Formatter('%(message)s')
  consoleHandler = logging.StreamHandler(sys.stdout)
  consoleHandler.setFormatter(formatter)
  logger.addHandler(consoleHandler)

  parser = argparse.ArgumentParser(description='Journera Event Generator')
  parser.add_argument('-k', '--key', required=True, default='ClientKey', help='Client Key')
  parser.add_argument('-s', '--secret', default=None, help='Secret Key')
  parser.add_argument('-i', '--industry', required=True, help='Industry (air,hotel,car)')
  parser.add_argument('-a', '--action', required=True, help='Action')
  parser.add_argument('-c', '--customerId', required=True, help='Customer Id')
  parser.add_argument('-r', '--reservationId', required=True, help='Reservation Id')
  parser.add_argument('-P', '--prod', action='store_true', help='Send to Prod')
  parser.add_argument('-S', '--stage', action='store_true', help='Send to Staging')
  parser.add_argument('-D', '--dev', action='store_true', help='Send to Dev')

  args = parser.parse_args()

  if not args.prod and not args.stage and not args.dev:
    log.info('Please choose -P prod or -S stage')
    sys.exit(1)

  if not args.secret:
    args.secret = getpass.getpass('-> Enter your SecretKey: ')

  log.info(parser.description)
  log.info('-- Event Generator ------------')
  log.info('Industry:       %s', args.industry)
  log.info('Action:         %s', args.action)
  log.info('Customer Id:    %s', args.customerId)
  log.info('Reservation Id: %s', args.reservationId)
  log.info('-------------------------------')

  genReq = {
	  'Industry': args.industry,
	  'Action': args.action,
	  'CustomerId': args.customerId,
	  'ReservationId': args.reservationId
  }

  method = 'POST'
  path = '/publish/v1/generate'
  timestamp = '%d' % time.time()
  nonce = str(uuid.uuid4())

  url = 'https://api.journera.com'
  if args.stage:
    url = 'https://api.stag.journera.com'
  if args.dev:
    url = 'http://localhost'
  url += path

  stringToSign = '%s\n%s\n%s\n%s\n' % (method, path, timestamp, nonce)
  signature = hmac.new(bytes(args.secret, 'UTF-8'), bytes(stringToSign, 'UTF-8'), hashlib.sha256).hexdigest()
  auth = 'hmac ck=%s,ts=%s,n=%s,sig=%s' % (args.key, timestamp, nonce, signature)

  headers = {
    'Content-type': 'application/json',
    'Authorization': auth
  }

  payload = bytes(json.dumps(genReq), 'UTF-8')
  req = urllib.request.Request(url, data=payload, headers=headers, method='POST')
  try:
    rsp = urllib.request.urlopen(req)
    log.info('success!')
  except urllib.error.URLError as e:
    rspData = e.read().decode('utf8', 'ignore')
    log.error('failed: %s', rspData)
