# controller.py https://www.bogotobogo.com/python/python_network_programming_server_client.php
import socket
import time
from multiprocessing import Process
from APIs import *
import psutil
import os

import ast
import tkinter as tk
from tkinter import filedialog, simpledialog
import wget
import config
from PIL import Image

# create a socket object
serversocket = socket.socket(
	        socket.AF_INET, socket.SOCK_STREAM)

# get local machine name
host = socket.gethostname()

port = 12468

# bind to the port
serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)
print("Controller Initialized")
CompCostFlag=False
while True:
    # establish a connection
    clientsocket, addr = serversocket.accept()
    # print("Got a connection from %s" % str(addr))
    # currentTime = time.ctime(time.time()) + "\r\n"
    data=clientsocket.recv(1024)
    message=data.decode()
    message = message.split()
    if not data: break
    if "help" in message[0].lower():
        ### to be updated
        print(" ----------------------------------------")
        print(" this program is the implementation of NNW in the AIF")
        print(" you can run AIM/AIW by sending 'run XX' ")
        print(" you can pause AIM/AIW by sending 'stop XX' ")
        print(" you can resume AIM/AIW by sending 'resume XX' ")
        print(" you can obtain the status of AIM/AIW by sending 'status XX' ")
        print(" you can end the program by typing 'exit'")
        print(" ----------------------------------------")

    elif "wget" in message[0].lower():
        test=wget.download(message[1])
        print(type(test))

    elif "getparse" in message[0].lower():

        #print(type(message[1]),message[1]) #always str

        root = tk.Tk()
        root.withdraw()
        filename = filedialog.askopenfilename(title='Select the zip (json and AIMs)', filetypes=(("Text files",
                                                                                             "*.zip"),
                                                                                            ("all files",
                                                                                             "*.*")))
        json_dict = MPAI_AIFS_GetAndParseArchive(filename)
        time.sleep(.5)
        import AIW.AIMs_files as AIMs_file
        config.AIM_dict = json_dict['SubAIMs']
        config.Topology = json_dict['Topology'] ### topology

        for i in range(len(json_dict['SubAIMs'])):
            config.AIMs[config.AIM_dict[i]["Name"]] = getattr(AIMs_file, config.AIM_dict[i]["Name"])()

        ### AIMs file should be in the .zip
        # print(AIMs.keys())
        # print(config.Topology)
        print(".json parsed")

    elif 'write' in message[0].lower():
        ## message[1] AIM_name, message[2] port_name, message[3] what to write
        MPAI_AIFM_Port_Input_Write(message[1],message[2],message[3])
    elif "read" in message[0].lower():
        ## message[1] AIM_name, message[2] port_name
        result=MPAI_AIFM_Port_Output_Read(message[1],message[2])
        print(message[2], "of", message[1], ":", result, type(result))
    elif "reset" in message[0].lower():
        ## message[1] AIM_name, message[2] port_name
        MPAI_AIFM_Port_Reset(message[1],message[2])

    elif 'run' in message[0].lower():
        for elements in config.Topology:
            # print(elements)
            if elements["Output"]["AIMName"]=="": ## no outputs means it's an input
                ### TBD better: if conditions link to the port reading
                root = tk.Tk()
                root.withdraw()
                path = filedialog.askopenfilename(title='Select '+str(elements["Input"]["PortName"]))

                MPAI_AIFM_Port_Input_Write(elements["Input"]["AIMName"], elements["Input"]["PortName"],
                                           path)
            else:
                MPAI_AIFM_AIM_Start(elements["Output"]["AIMName"])
                if elements["Input"]["AIMName"]=="": ## no inputs means it's an output
                    print("Output of",elements["Output"]["AIMName"],"- port",elements["Output"]["PortName"] )
                    print()
                    print(MPAI_AIFM_Port_Output_Read(elements["Output"]["AIMName"],elements["Input"]["PortName"]))
                    print()
                else:
                    MPAI_AIFM_Port_Input_Write(elements["Input"]["AIMName"], elements["Input"]["PortName"],
                                           MPAI_AIFM_Port_Output_Read(elements["Output"]["AIMName"],elements["Output"]["PortName"]))


    elif 'status' in message[0].lower():
        print(config.dict_process)
        MPAI_AIFM_AIM_GetStatus(message[1])
    elif 'pause' in message[0].lower():
        MPAI_AIFM_AIM_Pause(message[1])
    elif 'resume' in message[0].lower():
        MPAI_AIFM_AIM_Resume(message[1])

    elif 'stop' in message[0].lower():
        if message[1].lower() in config.dict_process:
            config.dict_process[message[1]].terminate()
            print( message[1], "stopped")
        else:
            print(message[1], "isn't running")
    elif "exit" in message[0].lower():
        print("ending session...")

        break
    else:
        print("input not implemented")
    clientsocket.close()
print("session ended")

### TO DO https://docs.python.org/3/library/multiprocessing.html
