import requests
import json
import os
import time
import sys
sys.path.insert(1, os.path.expanduser("~")+'/shell')
import gvs_cf





data = {'grant_type':"client_credentials",
        'resource':"https://graph.microsoft.com",
        'client_id':gvs_cf.onedrive_client_id,
        'client_secret':gvs_cf.onedrive_client_secret}
URL = gvs_cf.onedrive_generate_token_url
r = requests.post(url = URL, data = data)
j = json.loads(r.text)


TOKEN = j["access_token"]

onedrivefolder=sys.argv[2]
filepath=sys.argv[1]
uploadfilename=sys.argv[3]



URL = gvs_cf.onedrive_folder_url+onedrivefolder+"/"
headers={'Authorization': "Bearer " + TOKEN}
r = requests.get(URL, headers=headers)
    
def upload_file(filename,headers):

        upload_session = requests.post(URL+"/"+filename+":/createUploadSession", headers=headers).json()


        file_path = os.path.join(root,filename)

        with open(file_path, 'rb') as f:
            total_file_size = os.path.getsize(file_path)
            chunk_size = 327680
            chunk_number = total_file_size//chunk_size
            chunk_leftover = total_file_size - chunk_size * chunk_number
            i = 0
            while True:
                chunk_data = f.read(chunk_size)
                start_index = i*chunk_size
                end_index = start_index + chunk_size
                #If end of file, break
                if not chunk_data:
                    break
                if i == chunk_number:
                    end_index = start_index + chunk_leftover
                header = {'Content-Length':'{}'.format(chunk_size),'Content-Range':'bytes {}-{}/{}'.format(start_index, end_index-1, total_file_size)}
                chunk_data_upload = requests.put(upload_session['uploadUrl'], data=chunk_data, headers=header)
                #print(chunk_data_upload)
                #print(chunk_data_upload.json())
                i = i + 1
        # os.remove(os.path.join(root, filename))

directory=filepath


for root, dirs, files in os.walk(directory):
    i=0
    # print(uploadfilename)

    for filename in files:

        if filename != uploadfilename:
                    continue
        size=os.stat(directory+"/"+filename).st_size/1024

        if size <= 4096:
            filepath = os.path.join(root,filename)
            #print("Uploading "+filename+"....")
            fileHandle = open(filepath, 'rb')
            r = requests.put(URL+"/"+filename+":/content", data=fileHandle, headers=headers)
            fileHandle.close()
            # if r.status_code == 200 or r.status_code == 201:
            #   os.remove(os.path.join(root, filename))
        else:
            upload_file(filename,headers)
        time.sleep(1)
        break
print("done")
