from os import listdir, system
from os.path import isdir, join


import  multiprocessing as mp
from multiprocessing.sharedctypes import Value
import threading
import datetime
from time import gmtime, strftime, mktime
import time

array = []

def executeFile(value, index):
    start = time.time()
    #file1 = join(value[0], str(value[1]), str(value[2]), str(value[3]) + ".png")
    file1 = join(value[0], str(value[1]), str(value[2]), str(value[3]) + "O.png")

    file2 = join(value[0], str(value[1]), str(value[2]+1), str(value[3]) + "O.png")
    file3 = join(value[0], str(value[1]), str(value[2]), str(value[3]+1) + "O.png")
    file4 = join(value[0], str(value[1]), str(value[2]+1), str(value[3]+1) + "O.png")
    file5 = join(value[0], str(value[1]-1), str(int(value[2]/2)), str(int(value[3]/2)) + "O-512.png")
    command = "montage " + file1 + " " + file2 + " " + file3 + " " + file4 + " -geometry 256x256 " + file5
    #command = "cp " + file1 + " " + file2
    system(command)
    end = time.time()

    print("Time elapsed: " + str(end-start))

def acquireFile(array, val, i):
    if (i >= val.value):
        return -1;

    value = array[i]

    return value

def mainThread(index, array,v):
    import psutil
    
    val = v
    p = psutil.Process()
    p.cpu_affinity([index])
    print("HI!")
    n1 = datetime.datetime.now()
    i = index
    mutex = theMutex
    mutex.acquire()
    value = acquireFile(array,val, i)
    mutex.release()

    while value != -1:
        executeFile(value, index)
        i += 8
        mutex.acquire()
        value = acquireFile(array, val, i)
        mutex.release()

 
    n2 = datetime.datetime.now() 
    print str((mktime(n2.timetuple())-mktime(n1.timetuple())))

myPath = "."

for topdir in listdir(myPath):
    if (isdir(join(myPath, topdir))) and topdir.isdigit():
        topdirIndex = int(topdir)
        if (topdirIndex == 9):
        #if (topdirIndex > 0 and topdirIndex < 10):
            for middir in listdir(join(myPath, topdir)):
                if (isdir(join(myPath, topdir, middir))) and middir.isdigit():
                    middirIndex = int(middir)

                    if (middirIndex % 2) == 0:
                        for lowdir in listdir(join(myPath, topdir, middir)):
                            lowfile = lowdir.split(".")[0]
                            
                            if (lowfile.isdigit()):
                                lowfileIndex = int(lowfile)

                                if ((lowfileIndex % 2) == 0):
                                    array.append((myPath, topdirIndex, middirIndex, lowfileIndex))

threads = []
theMutex = threading.Lock()

# noinspection PyProtectedMember
pool = mp.Pool()
v = Value("i", len(array))
workers = pool._processes
print("Running pool with " + str(workers) + " workers")
for i in range(workers):
    p = mp.Process(target=mainThread, args=(i, array, v))
    p.start()
    #handler = pool.apply_async(mainThread, args=(i,array))
    #handler.get()
# Wait for children to finnish
#pool.close()
#pool.join()

#for i in range(2):
#    t = threading.Thread(target=mainThread,args=[theMutex])
#    threads.append(t)
#    t.start()
