import requests, json, pprint

pp = pprint.PrettyPrinter(indent=4)

AUTH_URL = 'https://developer.api.autodesk.com/authentication/v1/authenticate'
PHOTO_SCENE_URL = 'https://developer.api.autodesk.com/photo-to-3d/v1/photoscene'
PHOTO_UPLOAD_URL = 'https://developer.api.autodesk.com/photo-to-3d/v1/file'
PHOTO_PROCESSOR_URL = 'https://developer.api.autodesk.com/photo-to-3d/v1/photoscene/'

config = {}

def authenticate(conf):
    req = requests.post(
        AUTH_URL,
        headers={'Content-Type': 'application/x-www-form-urlencoded'},
        data = {
            'client_id': conf['client_id'],
            'client_secret': conf['client_secret'],
            'grant_type': 'client_credentials',
            'scope': 'data:write data:read'
        }
    )
    conf.update({'access_token':json.loads(req.content)['access_token']})
    return conf


def createPhotoScene(conf):
    photoSceneReq = requests.post(
        PHOTO_SCENE_URL,
        headers = {
            'Authorization':'Bearer '+conf['access_token'],
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data = {
            'scenename':'recon_3d_scene',
            'format': 'rcs,obj,ortho,fbx',
            "metadata_name[0]": "orthogsd",
              "metadata_value[0]": "0.1",
              "metadata_name[1]":  "orthocrop",
              "metadata_value[1]": "0.25",
              "metadata_name[2]": "targetcs",
              "metadata_value[2]": "UTM84-32N"
        }
    )

    #print(photoSceneReq,'\n', photoSceneReq.headers, photoSceneReq.content)
    conf.update({'photo_scene_id':json.loads(photoSceneReq.content)['Photoscene']['photosceneid']})
    return conf


def uploadImages(conf):
    data = {
            'photosceneid': conf['photo_scene_id'],
            'type': 'image',
    }

    for i in range(43,94, 4):
        url = 'http://rcsmike.com/assets/img/pot'+str(i)+'.jpg'
        print(url)
        data.update({'file['+str(i)+']': url})
    print(len(data), data)

    result = requests.post(
        PHOTO_UPLOAD_URL,
        headers = {
            'Authorization':'Bearer '+conf['access_token'],
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data = data
    )

    print('FILE UPLOAD', result.content)
    return result.status_code == 200


def process3d(conf):
    req = requests.post(
        PHOTO_PROCESSOR_URL + conf['photo_scene_id'],
        headers = {
            'Authorization':'Bearer '+conf['access_token'],
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    )

    print('process request result', req.content)

    processMsg = json.loads(req.content)['msg']
    if processMsg == 'No error':
         # make first poll request
        req = requests.get(
            PHOTO_PROCESSOR_URL + conf['photo_scene_id'] +'/progress',
            headers = {
                'Authorization':'Bearer '+conf['access_token'],
                      'Content-Type': 'application/json'
              
            }
        )

        # Continously process it
        jsonRet = json.loads(req.content)
        print('json raw', req.content)
        while float(jsonRet['Photoscene']['progress']) < 100.0:
            #print('progress',float(jsonRet['Photoscene']['progress']))
            req = requests.get(
            PHOTO_PROCESSOR_URL + conf['photo_scene_id'] +'/progress',
                headers = {
                    'Authorization':'Bearer '+conf['access_token'],
                          'Content-Type': 'application/json'
                }
            )
            print('json raw', req.content)
            jsonRet = json.loads(req.content)

        print('get obj url',PHOTO_PROCESSOR_URL + conf['photo_scene_id'] +'?format=obj')
        # now get obj file-- make another request to download obj file
        req = requests.get(
            PHOTO_PROCESSOR_URL + conf['photo_scene_id'] +'?format=obj',
                headers = {
                    'Authorization':'Bearer '+conf['access_token'],
                    'Content-Type': 'application/json'
                }
            )

        #print('download request',req.content, req.status_code, json.loads(req.content))
        downloadLink = json.loads(req.content)['Photoscene']['scenelink']
        print("download link is", downloadLink)
        return requests.get(downloadLink)
    else: 
        print("PROCESSING_ERROR", processMsg)
    
    return None


def main():
    # read config file for authentication
    config = open('../autodesk.config.json').read()
    config = json.loads(config)
    
    # authenticate app --gets access token needed for other stuff
    config = authenticate(config)
    # create photo scene
    config = createPhotoScene(config)
    pp.pprint(config)
    # upload images 
    if uploadImages(config) == True:
        print('Uploded images. Ready for processing....')
        # process images
        obj = process3d(config)
        print(obj)


if __name__ == '__main__':
    main()