#!/usr/bin/python
#-*-coding: utf-8-*-

"""Version: v0.1
Description: this program was developed in order to get informations
on all studied species'genes available on the Genoscope server. It runs only in Python 2.7.
Authors: alexandra.bomane@laposte.net, mel.colombier@free.fr
Usage: python -org organism gene2reaction_from_genoscope.py [-o outfile_name] [--output_file outfile_name] [-org organism_name]
Options:
    -h  Display full help message
    -help
        Same as -h
    -o outfile_name
        If no output file is specified, the standard output is used.
    --output_file outfile_name
        Same as -o
    -org organism_name
        Chosen organism to get its informations
"""

import json #For parsing the server response
import time #To add the current date to the standard file name
import argparse #To add options
from workflows_functions import RequestGenoscope #To send our request to the Genoscope server

if __name__=='__main__':

    print "; Job started", time.strftime("%Y-%m-%d_%Hh%M")

    try:
        #Current date
        date = time.strftime("%Y_%m_%d")

        # ext is the extension of the url request
        ext = "/organisms/list"

        # A JSON object is returned
        content = RequestGenoscope(ext)

        #Creation of arguments
        parser = argparse.ArgumentParser(add_help = True)
        parser.add_argument('-o','--output_file', action = 'store', dest = 'outfile_n', default = False, help = 'The user can choose the outfile name')
        parser.add_argument('-org', action = 'store' , dest = 'organism', default = None, help = 'The user\'s chosen organism')
        args = parser.parse_args()

        organism, outfile_n  = args.organism, args.outfile_n

        # Choose of outfile name
        if outfile_n:
            outfile = outfile_n #File name chosen by the user
        else:
            outfile = "gene2reaction_from_genoscope_" + date + ".tab" #Standard file name according to the date

        #Getting of the JSON object
        decoded = json.loads(content)

        #Creation of a dictionary containing some informations about the studied organism such as its Genoscope ID, its NCBI ID and its name
        info_species = {}

        #Feeding of the dictionary
        for i in range(len(decoded)):
            dict_species = decoded[i]
            if organism in dict_species[u'odirname']:
                info_species['GenoscopeID'] = str(dict_species[u'oid'])
                info_species['NcbiID'] = str(dict_species[u'otaxon'])
                info_species['Organism Name'] = str(dict_species[u'oname'])

        #New request to get more informations
        org_id = info_species['GenoscopeID']
        ext = "/genomes/genomic-objects/list/" + org_id
        content2 = RequestGenoscope(ext)

        #Getting of the JSON object : here it is an array containing dictionaries
        decoded2 = json.loads(content2)

        #Creation of the tabulated file
        f = open(outfile,'w')

        f.write('Gene Name' + '\t' 'Synonyms' + '\t' + 'EC' + '\t' + 'goOriId' + '\t' + 'Reaction' + '\t' + 'go Id' + '\t' + 'Function' + '\t' + 'Product type' + '\t' + 'Process' + '\t' + 'Product' + '\n')

        #From this array, we get the dictionary containing our most important informations
        for i in range(len(decoded2)):
            dict_genes = decoded2[i]
            ss_dict = dict_genes[u'genomicObject']

        #file_content contains the strings of interesting values from ss_dict
            file_content = str(ss_dict[u'goGeneName']) + '\t' + str(ss_dict[u'goSynonyms']) + '\t' + str(ss_dict[u'goEc']) + '\t' + str(ss_dict[u'goOriId']) + '\t' + str(ss_dict[u'goReaction']) + '\t' + str(ss_dict[u'goId']) + '\t' + str(ss_dict[u'goFunction']) + '\t' + str(ss_dict[u'goProductType']) + '\t' + str(ss_dict[u'goProcess']) + '\t' + str(ss_dict[u'goProduct'])

            f.write(file_content + '\n')

        f.close()
        # Il ne reste plus qu'a trier les informations et l'ecrire dans un fichier.

        print "; Job done, Job name :", outfile, time.strftime("%Y-%m-%d_%Hh%M")

    except TypeError:
        print "Enter an organism's name in argument, please ! \nRecall : -org My_Organism_Name"



