import requests
import untangle
import socket
import sys
import time
import random
import json
import getopt
from urllib3.exceptions import InsecureRequestWarning
from urllib3 import disable_warnings
disable_warnings(InsecureRequestWarning)
from paho.mqtt import client as mqtt_client
import datetime

jobId = "0ceadf5e-0b9e-11ed-9806-9a2cbecf0a5f"
try:
    opts, args = getopt.getopt(sys.argv[1:], "cT:", ["command=", "help", "output="])
except getopt.GetoptError as err:
    # print help information and exit:
    print(str(err))  # will print something like "option -a not recognized"
    #usage()
    sys.exit(2)
output = None
# QJ : getopts
_ACTION = "default"
for o, a in opts:
    if o == "-c":
        _ACTION = "check"
    elif o in ("-p", "--publish"):
        _PUBLISH = True
    elif o in ("-m", "--publish"):
        _MESSAGE = a
    elif o in ("-t", "--publish"):
        _TOPIC = a
    elif o in ("-S", "--setvar"):    
        _SETVAR = True
        _THR_NAME = sys.argv[2]
        _THR_VAL = sys.argv[3]
    elif o in ("-T", "--task"):
        if a == "task1":
            jobId = "0ceadf5e-0b9e-11ed-9806-9a2cbecf0a5f"
        elif a == "task2":
            jobId = "1bba7e36-6ea9-11ed-91cb-d63dc5df381e"
    else:
        _WIZZARD = True
nasIp = "192.168.77.106"
nasPort = "4443"
user = "jaydee"
password = "l4c1j4yd33Du5lo"

def get_sid():
    headers = {"Content-type": "application/x-www-form-urlencoded"}
    params = {
        "user": "jaydee",
        "serviceKey": 1,
        "pwd": "bDRjMWo0eWQzM0R1NWxv"
    }
    url = "https://{}:{}/cgi-bin/authLogin.cgi".format(nasIp, nasPort)

    response = requests.get(url, headers=headers, params=params, verify=False)
    
    #print("Status Code", response.status_code)
    #print("JSON Response ", response.text)
    obj = untangle.parse(response.text)
    sid = (obj.QDocRoot.authSid.cdata)
    return sid

def check_status():
    sid = get_sid()
    headers = {"X-QNAP-SID": sid}
    params = {}

    url = "https://{}:{}/cc3/v1/users/system/jobs".format(nasIp, nasPort)
    response = requests.get(url, headers=headers, params=params, verify=False)
    
    
    
    # print("JSON Response ", response.text)
    data = json.loads(response.text)
    wait_for_done = True
    while wait_for_done: 
        for i in data["jobs"]:
                
                #print(i["_id"])
                #print(data["jobs"][i]["_id"])
                if i["_id"] == jobId:
                    # print(i)
                    print(i["statistics"]["progress"])
                    time.sleep(3)
    
    
    '''
    auth=$(curl --insecure "https://$nasIp/cgi-bin/authLogin.cgi" -H "Content-type: application/x-www-form-urlencoded" --data-urlencode "user=$user" --data-urlencode "serviceKey=1" --data-urlencode "pwd=$(echo -n $password | base64)" --silent) 
    echo $auth
    sidXML=$(echo "$auth" | grep -Eo "<authSid>(.+?)</authSid>")
    sidStrip="${sidXML/<authSid><![CDATA[/}"
    sid="${sidStrip/]]><\/authSid>/}"
    curl "https://$nasIp/cc3/v1/users/system/jobs/$1?command=start" -H "X-QNAP-SID: $sid" --data-raw '{}' --silent --insecure
    curl 'https://192.168.77.106:4443/cc3/v1/users/system/jobs' -H 'X-QNAP-SID: r299e6x3' --silent --insecure
    '''
    
    
    
if _ACTION == "default":
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    service_online = False
    broker = '192.168.77.106'
    port = 1883
    topic = "sectorq/systems/hbs"
    mqtt_username = 'jaydee'
    mqtt_password = 'jaydee1'

    while not service_online:
        result = sock.connect_ex(('192.168.77.189',873))
        if result == 0:
            print("Port is open")
            service_online = True
        else:
            print("Port is not open")
            time.sleep(5)
    sock.close()

    sid = get_sid()

    #print("-----------------")
    #print(sid)
    #print("-----------------")

    headers = {"X-QNAP-SID": sid}
    params = {}

    url = "https://{}:{}/cc3/v1/users/system/jobs/{}?command=start".format(nasIp, nasPort, jobId)
    #print(url)
    response = requests.post(url, headers=headers, params=params, verify=False)

    
    #print("Status Code", response.status_code)
    #print("JSON Response ", response.text)
    client = mqtt_client.Client()
    client.username_pw_set(mqtt_username, mqtt_password)
    client.connect(broker,1883,60)
    msg = {"status":"initializing","start_time":"now","progress":0}
    client.publish(topic, json.dumps(msg));
    client.disconnect();

    wait_for_done = True
    task1_done = False
    task2_done = False
    url = "https://{}:{}/cc3/v1/users/system/jobs".format(nasIp, nasPort)
    client = mqtt_client.Client()
    client.username_pw_set(mqtt_username, mqtt_password)
    client.connect(broker,1883,60)

    while wait_for_done: 
        response = requests.get(url, headers=headers, params=params, verify=False)
        print("Status Code", response.status_code)
        #print("JSON Response ", response.text)
        data = json.loads(response.text)
        # print(data["jobs"])
        for i in data["jobs"]:
            time.sleep(3)
            #print(i["_id"])
            #print(data["jobs"][i]["_id"])
            #if i["_id"] == jobId:
                # print(i)
                # print(i["statistics"])

                try:
                    msg = {"status":i["statistics"]["status"],"name":i["name"],"start_time":i["statistics"]["start_time"],"stop_time":i["statistics"]["stop_time"],"elapsed_time":str(datetime.timedelta(seconds=round(i["statistics"]["elapse_time"],0))),"progress":i["statistics"]["progress"]}
                    
                except:
                    msg = {"status":i["statistics"]["status"],"name":i["name"],"start_time": i["statistics"]["start_time"]}
                client.publish(topic, json.dumps(msg));
                if i["statistics"]["status"] == "Finished":
                    wait_for_done = False
                    
    client.disconnect();
    #curl "https://$nasIp/cc3/v1/users/system/jobs/$1?command=start" -H "X-QNAP-SID: $sid" --data-raw '{}' --silent --insecure



    
if _ACTION == "check":
    check_status()