import os
import json
from zipfile import ZipFile
import psutil
global error_t
from multiprocessing import Process
import config

error_t=True
def MPAI_AIFS_GetAndParseArchive(filename):
    '''filename is a zipfld with at least a ".json"
    :return the data structure'''
    i = filename.find(".")
    os.makedirs(filename[:i],exist_ok=True)
    with ZipFile(filename, 'r') as zObject:
        # Extracting all the members of the zip
        # into a specific location.
        zObject.extractall(
            path=filename[:i])
    for files in os.listdir(filename[:i]):
        if '.json' in files:
            json_file = open(filename[:i]+"/"+files)
            return json.load(json_file)
    return error_t

def MPAI_AIFU_Controller_Initialize():
    '''initialize the controller and switch it on'''
    return

def MPAI_AIFU_Controller_Destroy():
    '''switch of controller'''
    return

def MPAI_AIFM_AIM_Start(name):
    '''start AIW named name (after parse),
    :return AIW_ID (int)'''

    p1 = Process(target=config.AIMs[name].run())
    p1.start()  ### run it somewhere
    config.dict_process[name.lower()] = p1
    return

def MPAI_AIFM_AIM_Pause(name):
    '''Pause AIW named name with AIW_ID'''
    if name in config.dict_process:
        temp_p = psutil.Process(config.dict_process[name].pid)
        temp_p.suspend()
        print(name, "paused")
    else:
        print(name, "isn't running")
    return error_t

def MPAI_AIFM_AIM_Resume(name):
    '''Resume AIW named name with AIW_ID'''
    if name.lower() in config.dict_process:
        temp_p = psutil.Process(config.dict_process[name].pid)
        temp_p.resume()
        print(name, "resumed")
    else:
        print(name, "isn't running")
    return error_t

def MPAI_AIFM_AIM_Stop(name):
    '''Stop AIW named name with AIW_ID'''
    if name.lower() in config.dict_process:
        config.dict_process[name].terminate()
        print(name, "stopped")
    else:
        print(name, "isn't running")
    return

def MPAI_AIFM_AIM_GetStatus(name):
    '''current state of the AIM named name in AIW_ID
    :return status(int) [MPAI_AIM_ALIVE, MPAI_AIM_DEAD]'''
    if name.lower() in config.dict_process:
        print("status of %s: %s" % (name, str(config.dict_process[name].is_alive())))
    else:
        print(name, "was never initiated")
    return error_t

def MPAI_AIFM_Port_Input_Write(AIM_name,port_name, message):
    setattr(config.AIMs[AIM_name],port_name,message)
    return error_t

def MPAI_AIFM_Port_Output_Read(AIM_name,port_name):
    result=getattr(config.AIMs[AIM_name],port_name)
    return result

def MPAI_AIFM_Port_Reset(AIM_name,port_name):
    setattr(config.AIMs[AIM_name],port_name,None)
    return error_t