#!/usr/bin/env python

import os
import sys
import argparse
import shutil

import cube_model
import file_format


def initialize_sas_file(dest):
    filename = 'rubiks_cube.sas'
    path = dest + filename
    if os.path.exists(path):
        new_path = dest + 'old_' + filename
        shutil.move(path, new_path)

    return open(path, 'w+')


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--size', type=int, help='set the cube size', default=3)
    parser.add_argument('-m', '--moves', type=str,
                        help='takes one argument (prime/double/all) to add operations to the cube', default=None)
    parser.add_argument('-d', '--dest', type=str, help='puts output files in the specified path',
                        default=(os.getcwd() + '/files'))
    parser.add_argument('-t', '--turns', type=int, help='define the number of turns to shuffle the cube', default=2)
    parser.add_argument('-p', '--problem', type=str,
                        help='path to a file containing the maneuver notation to initialize the cube', default=None)
    parser.add_argument('-c', '--combine', help='combine position and rotation of each cubie in one variable',
                        action='store_true')

    args = parser.parse_args()

    n = args.size
    if n < 2:
        print('invalid size: must be 2 or higher')
        sys.exit(1)
    turn_options = [1]
    if args.moves is not None:
        if args.moves == 'prime':
            turn_options += [3]
        elif args.moves == 'double':
            turn_options += [2]
        elif args.moves == 'all':
            turn_options += [2, 3]
    dest = args.dest
    problem = None
    if args.problem is None:
        problem = args.turns
    else:
        if not os.path.exists(args.problem):
            print('''The specified problem file does not exist. Problem generated randomly.''')
        else:
            with open(args.problem, 'r') as file:
                problem = file.read()

    os.system('mkdir ' + dest)
    if not dest.endswith('/'):
        dest = dest + '/'

    cube = cube_model.CubeModel(n)
    goal_cube = cube_model.CubeModel(n)

    file = initialize_sas_file(dest)

    if args.combine:
        fileformat = file_format.Combined(cube, goal_cube, problem, turn_options, file)
    else:
        fileformat = file_format.Separated(cube, goal_cube, problem, turn_options, file)

    fileformat.write()


if __name__ == '__main__':
    main()
