from itertools import chain

from copy import deepcopy

from gooey.util.functional import compact


def buildCliString(target, cmd, positional, optional, suppress_gooey_flag=False):
    positionals = deepcopy(positional)
    if positionals:
        positionals.insert(0, "--")

    cmd_string = ' '.join(compact(chain(optional, positionals)))

    if cmd != '::gooey/default':
        cmd_string = u'{} {}'.format(cmd, cmd_string)

    # windows fixes
    import sys
    import os
    if sys.platform == "win32":
        target_splitted = target.split(' ')
        cryolo_cmd = target_splitted[2]
        cryolo_cmd_splitted = os.path.splitext(cryolo_cmd[1:-1])
        if cryolo_cmd_splitted[1] == '':
            cryolo_cmd = cryolo_cmd_splitted[0] + '.exe'
            target_splitted[2] = f"\"{cryolo_cmd}\""
            target = ' '.join(target_splitted)


    ignore_flag = '' if suppress_gooey_flag else '--ignore-gooey'
    return u'{} {} {}'.format(target, ignore_flag, cmd_string)
