import os
import shutil
import hashlib


def md5checksum(filepath):
    file = open(filepath, 'r')

    content = file.read()
    hash = hashlib.md5(content.encode())
    return hash.hexdigest()


def main():
    filedirectory = 'problems/'
    if os.path.exists(filedirectory):
        shutil.rmtree(filedirectory)
    os.system('mkdir ' + filedirectory)

    scrambledirectory = 'scramble/'
    os.system('mkdir ' + scrambledirectory)

    hash_table = []
    filepath = 'files/rubiks_cube.sas'
    scramblepath = 'files/rubiks_cube.scramble'

    max_turns = 20
    for i in range(max_turns):
        for j in range(10):
            while True:
                # If only single clockwise turns were allowed, the case i=1 would need to be treated separately, since
                # only 6 different files can be generated.
                scramblefile = scrambledirectory + 'turns=' + str(i + 1) + '_problem=' + str(j) + '.scramble'
                if os.path.exists(scramblefile):
                    os.system('python build.py -s 3 -m all -c -t' + str(i + 1) + ' -p ' + scramblefile)
                else:
                    os.system('python build.py -s 3 -m all -c -t' + str(i + 1))
                hash = md5checksum(filepath)
                if hash not in hash_table:
                    hash_table.append(hash)
                    break

            filename = 'rubikscube_size=3_turns=' + str(i + 1) + '_problem=' + str(j) + '.sas'
            os.system('mv {filepath} {filedirectory}{filename}'.format(**locals()))
            if not os.path.exists(scramblefile):
                os.system('mv {scramblepath} {scramblefile}'.format(**locals()))


if __name__ == '__main__':
    main()
