# -*- coding: utf-8 -*-
import time
import os, sys
import requests
# from rest_framework import status
from requests.auth import HTTPBasicAuth
import time
import zipfile


# upload all the images in the image_folder (by default the current folder ./) to the image server using post request
# the image server could create a db named with the combination of serviceid and taskid, like swt and 1001
def bulk_image_upload(image_folder=os.path.dirname(os.path.realpath(__file__)), image_server='http://11.239.188.5:8000/images/', serviceid='swt', taskid='ImageLib'):
    zip_file_path, image_num = zip_dir(image_folder, taskid)
    # zip_name = taskid + '.zip'
    print(zip_file_path)
    files = {'imagelist': open(zip_file_path, 'rb')}
    # example: image_send = {'file1': open('report.xls', 'rb'), 'file2': open('otherthing.txt', 'rb')}
    params_id = {'serviceid': serviceid, 'taskid': taskid}
    # image_server = str(image_server+serviceid+'/'+'taskid'+'/')
    print(image_server)
    response = requests.post(image_server, params=params_id, files=files, auth=HTTPBasicAuth('admin', 'password123'))
    print(response)
    return response.status_code, image_num


def zip_dir(image_folder=os.path.dirname(os.path.realpath(__file__)), taskid='ImageLib'):
    img_exts = ["png", "bmp", "jpg"]
    zip_name = str(taskid+'.zip')
    zip_file_path = os.path.join(image_folder, zip_name)
    if os.path.exists(zip_file_path):
        os.remove(zip_file_path)
    zipf = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
    abs_src = os.path.abspath(image_folder)
    image_num = 0
    for root, dirs, files in os.walk(image_folder):
        for filename in files:
            ext = filename[-3:].lower()
            if ext not in img_exts:
                continue
            absname = os.path.join(root, filename)
            arcname = absname[len(abs_src) + 1:]
            zipf.write(absname, arcname)
            image_num += 1
    zipf.close()
    return zip_file_path, image_num


if __name__ == "__main__":
    paramsLen = len(sys.argv)
    if paramsLen < 2:
        raise Exception("Params not enough! Use this script like this: python taskTimer.py serviceid taskid")

    servideid = sys.argv[1]
    taskid = sys.argv[2]
    print(taskid)

    time_start = time.time()
    response_status_code, image_num = bulk_image_upload(serviceid=servideid, taskid=taskid)
    # print(response_status_code == status.HTTP_201_CREATED)
    time_end = time.time()
    print("It costs %f sec to process all the %d images." % (time_end-time_start, image_num))
