#!/usr/bin/env python

# Copyright 2015 University of Chicago
# Licensed under the APL 2.0 license

# Process jobs that have been uploaded and create
# a pegasus workflow and submit
import argparse
import re
import sys
import os
import time
import subprocess
import fcntl

import cStringIO
import psycopg2

import Pegasus.DAX3
import fsurfer
import fsurfer.helpers
import fsurfer.log

PEGASUSRC_PATH = '/etc/fsurf/pegasusconf/pegasusrc'
VERSION = fsurfer.__version__
MAX_RUNNING_WORKFLOWS = 200


def pegasus_submit(dax, workflow_directory, output_directory):
    """
    Submit a workflow to pegasus

    :param dax:  path to xml file with DAX, used for submit
    :param workflow_directory:  directory for workflow information
    :param output_directory:  directory for workflow output
    :return:            the output from pegasus
    """
    try:
        output = subprocess.check_output(['/usr/bin/pegasus-plan',
                                          '--sites',
                                          'condorpool',
                                          '--dir',
                                          workflow_directory,
                                          '--conf',
                                          PEGASUSRC_PATH,
                                          '--output-dir',
                                          output_directory,
                                          '--dax',
                                          dax,
                                          '--submit'],
                                         stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as err:
        return err.returncode, err.output

    return 0, output


def submit_workflow(subject_files, version, subject_name, user, job_run_id,
                    multicore=True, options=None, workflow='diamond'):
    """
    Submit a workflow to OSG for processing

    :param subject_files:  lists with paths to files with MRI
                           data (mgz or subject dir)
    :param version:        FreeSurfer version to use
    :param subject_name:   name of subject being processed
    :param user:          freesurfer user that workflow is being run for
    :param job_run_id:         job run id for the workflow
    :param multicore:     boolean indicating whether to use a multicore
                          workflow or not
    :param options:       Options to pass to FreeSurfer
    :param workflow:      string indicating type of workflow to run (serial,
                          diamond, single)
    :return:              pegasus workflow id  on success, None on error
    """
    if multicore:
        cores = 8
    else:
        cores = 2
    logger = fsurfer.log.get_logger()

    logger.debug("Processing workflow using {0} as input".format(subject_files))
    dax = Pegasus.DAX3.ADAG('freesurfer')