import os
import inspect
import getpass
import subprocess
import sys
import re
import shutil

import cutlass
import anadama.pipelines

from collections import OrderedDict
from . import workflows
from . import PrepProt

def get_proteomes(preps):
	def _ps():
		for prep in preps:
			proteome_list=list()
			for proteome in prep.proteomes():
				proteome_list.append(proteome)
			if len(proteome_list)!= 0:
				yield prep, proteome_list
	return map(PrepProt._make, _ps())

# Utility function to check whether the required softwares are installed.
def check_software_dependencies():
	print('checking software dependencies')
	# Check if ASCP is installed
	try:
		return_status=subprocess.check_output(["ascp", "-A"])
	except OSError as e:
		print('ASCP not installed or configured. Please install/configure ASCP.')
		sys.exit(1)
	# Check if Java(x64) greater than version 1.8 is intalled
	try:
		return_status=subprocess.check_output(["java", "-d64", "-version"], stderr=subprocess.STDOUT)
	except subprocess.CalledProcessError as e:
		print('64-bit Java not installed. Please install 64-bit java.')
		sys.exit(1)
	version=re.findall('"([^"]*)"',return_status.splitlines()[0])[0]
	if version<'1.8':
		print("Java verson 1.8 or greater required.")
		sys.exit(1)


class PRIDEPipeline(anadama.pipelines.Pipeline):
	""" Pipeline for submitting proteomics data from iHMP DCC's OSDF instance
	to PRIDE repository.

	Steps:
	1. Given an OSDF id number for a Study, query the database to retrieve all the proteome
	instances included in the study.

	2. For each proteome instance retrieved, download the rsult file (in .mzid format) along
	with the related peak file (in .mgf format), raw data file(s) and other files(if present).

	3. Validate each set of result and related peak files using PRIDE Converter tool.

	5. Create a submission summary file (submission.px) required for submitting the data.

	6. Submit the entire set of files along with the submission file created in the previos
	step to the PRIDE respository
	"""
	name="PRIDE"

	default_options = {
		"collect": {
			"dcc_user": None,
			"dcc_pw": None,
			"study_id": None,
		},
		"submit": {
			"pride_user": None,
			"pride_pw": None,
			"pride_server": None,
			"pride_directory": None,
		}
	}

	workflows= {
		"collect": workflows.collect,
		"submit": workflows.submit,
	}

	project_metadata = OrderedDict([                 # Field populated from
		("submitter_name", None),                 # .anadama_pride config file
		("submitter_email", None),                # .anadama_pride config file
		("submitter_affiliation", None),          # .anadama_pride config file
		("lab_head_name", None),                  # .anadama_pride config file
		("lab_head_email", None),                 # .anadama_pride config file
		("lab_head_affiliation", None),           # .anadama_pride config file
		("submitter_pride_login", None),          # .anadama_pride config file
		("project_title", None),                  # .anadama_pride config file
		("project_description", None),            # .anadama_pride config file
		("sample_processing_protocol", None),     # Field 'protocol_steps' from
												  # corresponding assey_prep
		("data_processing_protocol", None),       # Field 'data_processing_protocol' from
												  # corresponding prodeome
		("keywords", ''),                         # Field 'species' from
												  # corresponding assey_prep
		("submission_type", 'COMPLETE'),          # Only 'Complete' submissions are done
											      # Thats the way of a 'Shinobi'.
		("experiment_type", list()),              # Field 'experiment_type' from
												  # corresponding assey_prep
		("species", list()),                      # Field 'species' from
												  # corresponding assey_prep
		("tissue", list()),                       # Field 'tissue' from
												  # corresponding assey_prep
		("instrument", list()),                   # Field 'instrument_name' from
												  # proteome OSDF entry
	])


	def __init__(self, workflow_options=dict(), *args, **kwargs):
		""""""
		super(PRIDEPipeline, self).__init__(*args, **kwargs)

		check_software_dependencies()
		config_file=None

		# Check if config file is present in the following places in order of precedence:
		# 1. User's Home directory
		# 2. The directory where the module code is present
		# 3. Any directory included in python path variable
		path=os.path.expanduser("~")
		file_path=os.path.join(path,'.anadama_pride')
		if config_file is None and os.path.exists(file_path):