import urllib.parse
import urllib.request
import json

def get_token():
    params = urllib.parse.urlencode({"username": "eric", "password":"<PASSWORD>"}).encode()
    contents = urllib.request.urlopen('http://democut3.canadaeast.cloudapp.azure.com/rest/ctcapi/v3/auth/login?' ,data=params)

    data = json.loads(contents.read().decode(contents.info().get_param('charset') or 'utf-8'))

    return data['token']

def create_Device():
    url = 'http://democut3.canadaeast.cloudapp.azure.com/rest/ctcapi/v3/devices'

    data = urllib.parse.urlencode({"deviceTypeKey": 113001, "externalId": "Test05", "name": "Test05", "serviceId": "db39fd3e-7ad5-44be-a817-01fcb608efbb", "smartObjects": [], "metas": {}}).encode()
    
    headers = {
        'x-access-token': '<KEY>'
        }
    
    req = urllib.request.Request(url, data=data)
    req.add_header('x-access-token', '<KEY>')
    response = urllib.request.urlopen(req)
    the_page = response.read()

    # req = urllib.request.Request('http://democut3.canadaeast.cloudapp.azure.com/rest/ctcapi/v3/devices?')
    # token = "<KEY>"
    # req.add_header('x-access-token', '<KEY>')

    # contents = urllib.request.urlopen(req, data=params)
    # import requests
    # from requests.auth import HTTPBasicAuth
    # # import json
    # # # request = Request
    # params = {
    #     "deviceTypeKey": 113001,
    #     "externalId": "Test01",
    #     "name": "Test01",
    #     "serviceId": "db39fd3e-7ad5-44be-a817-01fcb608efbb",
    #     "smartObjects": [],
    #     "metas": {}
    #     }

    # # # headers = 
    # response = requests.post(
    #     url, 
    #     data = params,
    #     header=('x-access-token','<KEY>'))

    # # params = urllib.parse.urlencode({
    # #     "deviceTypeKey": 126001,
    # #     "externalId": "Test01",
    # #     "name": "Test01",
    #     "serviceId": "db39fd3e-7ad5-44be-a817-<KEY>",
    #     "smartObjects": [],
    #     "metas": {}
    #     }).encode()
    # contents = urllib.request.urlopen('http://democut3.canadaeast.cloudapp.azure.com/rest/ctcapi/v3/devices',  data=params)
    
    # data = json.loads(contents.read().decode(contents.info().get_param('charset') or 'utf-8'))
    return the_page

if __name__ == '__main__':
    # token = get_token()
    # print(token)

    data = create_Device()
    print(data.content)
    print(data.text)
    print(data.status_code)
    print(data['id'])
