#!/usr/bin/env python
import argparse
import sys

import meshroom
meshroom.setupEnvironment()

import meshroom.core.graph
import meshroom.core.taskManager
from meshroom.core.node import Status


parser = argparse.ArgumentParser(description='Execute a Graph of processes.')
parser.add_argument('graphFile', metavar='GRAPHFILE.mg', type=str,
                    help='Filepath to a graph file.')
parser.add_argument('--node', metavar='NODE_NAME', type=str,
                    help='Process the node. It will generate an error if the dependencies are not already computed.')
parser.add_argument('--toNode', metavar='NODE_NAME', type=str,
                    help='Process the node with its dependencies.')
parser.add_argument('--forceStatus', help='Force computation if status is RUNNING or SUBMITTED.',
                    action='store_true')
parser.add_argument('--forceCompute', help='Compute in all cases even if already computed.',
                    action='store_true')
parser.add_argument('--extern', help='Use this option when you compute externally after submission to a render farm from meshroom.',
                    action='store_true')
parser.add_argument('--cache', metavar='FOLDER', type=str,
                    default=None,
                    help='Override the cache folder')

parser.add_argument('-i', '--iteration', type=int,
                    default=-1, help='')

args = parser.parse_args()

graph = meshroom.core.graph.loadGraph(args.graphFile)
if args.cache:
    graph.cacheDir = args.cache
graph.update()

if args.node:
    # Execute the node
    node = graph.findNode(args.node)
    submittedStatuses = [Status.RUNNING]
    if not args.extern:
        # If running as "extern", the task is supposed to have the status SUBMITTED.
        # If not running as "extern", the SUBMITTED status should generate a warning.
        submittedStatuses.append(Status.SUBMITTED)
    if not args.forceStatus and not args.forceCompute:
        if args.iteration != -1:
            chunks = [node.chunks[args.iteration]]
        else:
            chunks = node.chunks
        for chunk in chunks:
            if chunk.status.status in submittedStatuses:
                print('Warning: Node is already submitted with status "{}". See file: "{}"'.format(chunk.status.status.name, chunk.statusFile))
                # sys.exit(-1)
    if args.iteration != -1:
        chunk = node.chunks[args.iteration]
        chunk.process(args.forceCompute)
    else:
        node.process(args.forceCompute)
else:
    if args.iteration != -1:
        print('Error: "--iteration" only make sense when used with "--node".')
        sys.exit(-1)
    toNodes = None
    if args.toNode:
        toNodes = graph.findNodes([args.toNode])

    taskManager = meshroom.core.taskManager.TaskManager()
    taskManager.compute(graph, toNodes=toNodes, forceCompute=args.forceCompute, forceStatus=args.forceStatus)

