#!/usr/bin/env python

import sys
import json
from ttlockwrapper.ttlock import TTlockAPIError
from ttlockwrapper import TTLock,constants


'''
To call this script:
$ pip3 install ttlockio
$ create_user_and_access_token YOUR_TTLOCK_CLIENT_ID YOUR_TTLOCK_CLIENT_SECRET NEW_NAME_FOR_YOUR_USER NEW_PASS_FOR_YOUR_USER REDIRECT_URI
For "YOUR_TTLOCK_CLIENT_ID" and "YOUR_TTLOCK_CLIENT_SECRET", register at https://open.ttlock.com/reg 
"NEW_NAME_FOR_YOUR_USER" the name for your new user
"NEW_PASS_FOR_YOUR_USER" new pass for your new user  whit max 32 chars and low case
"REDIRECT_URI" Ex: https://yourdomain.com/
'''

clientId = str(sys.argv[1])
clientSecret = str(sys.argv[2])
user = str(sys.argv[3])
password = str(sys.argv[4])
redirect_url = str(sys.argv[5])
result = None
result_user=TTLock.create_user(clientId,clientSecret,user,password).get(constants.USER_FIELD)
if result_user==user:
    result = TTLock.get_token(clientId,clientSecret,user,password,redirect_url)
else:
    raise TTlockAPIError()

if result.get(constants.ACCESS_TOKEN_FIELD):
    result_json = '[{"ttlockclientapp":{}, ttlocktoken: {}, username: {},refreshtoken: {}}]'
    parsed = json.loads(result_json.format(clientId,result.get(constants.ACCESS_TOKEN_FIELD),result_user,result.get(constants.REFRESH_TOKEN_FIELD)))
    print(json.dumps(parsed, indent=2, sort_keys=False))
else:
    raise TTlockAPIError()

