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

"""Version: v0.1
Description: this program was developed in order to get informations 
on all studied species available on the Ensembl server. It runs only in Python 2.7.
Authors: alexandra.bomane@laposte.net, mel.colombier@free.fr
Usage: python supported_organisms_ensembl.py [-o outfile_name] [--output_file outfile_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
"""

import httplib2 #To send the request using http protocol
import sys
import json #For parsing the server response
import time #To add the current date to the standard file name
import argparse #To add options

if __name__=='__main__':
    
    #Current date
    date = time.strftime("%Y-%m-%d")
    
    print "; Job started", time.strftime("%Y-%m-%d_%Hh%M")
    
    #.cache is a file containing in memory all requests parameters such as the status, the url, the returned JSON object...  
    http = httplib2.Http(".cache")
     
    #Specify the url of the server 
    server = "http://beta.rest.ensembl.org"
    ext = "/info/species?"
    
    #Send the request to the server:
    resp, content = http.request(server + ext, method = "GET", headers = {"Content-Type":"application/json"})
     
    #Check the status of the request: 
    if not resp.status == 200:
        print "Invalid response: ", resp.status
        sys.exit()
    
    #Response return as a JSON object : here a dictionary 
    decoded = json.loads(content)
    
    #Creation of arguments 
    parser = argparse.ArgumentParser(add_help = True)
    parser.add_argument('-o', action = 'store', dest = 'outfile_n', default = False, help = 'The user can choose the outfile name')
    parser.add_argument('--output_file', action = 'store', dest = 'outfileN', default = False, help ='The user can choose the outfile name')
    args = parser.parse_args()
    
    outfile_n,outfileN = args.outfile_n, args.outfileN
    
    # Choose of the outfile name
    if outfile_n:
        outfile = outfile_n #File name chosen by the user
    elif outfileN:
        outfile = outfileN #File name chosen by the user
    else:
        outfile = "supported_organisms_ensembl_" + date + ".tab" #Standard file name according to the date
        
    #Creation of the tabulated file
    f = open(outfile,'w')
    
    f.write("Division" + '\t' + "Display Name" + '\t' + "Name" + '\t' + "Common name" + '\t' + "Assembly" + '\t' + "Groups" + '\t' + "Taxon_ID" + '\t' + "Release" + '\t' + "Aliases" + '\n')      
    
    for value in decoded.values():      
        list_dict_species = value       #list_dict_species is a list of dictionaries containing species informations 
    
    for i in range (len(list_dict_species)):
        dict_species = list_dict_species[i]          #dict_species is a dictionary containing informations about a given species
    
    #The value of dict_species[u'groups'] is a list : the for loop allows to display each element of this list without '[]'  
        the_groups = ""
        for group in dict_species[u'groups']:
            the_groups = the_groups + group + ',' + ' '
    
    #The value of dict_species[u'aliases'] is a list : the for loop allows to display each element of this list without '[]'    
        the_alias = ""     
        for alias in dict_species[u'aliases']:
            the_alias = the_alias + alias + ',' + ' '
    
    #file_content variable contents all strings matching to each value of the dictionary for a given species separated by tabulations    
        file_content = str(dict_species[u'division']) + '\t' + str(dict_species[u'display_name']) + '\t' + str(dict_species[u'name']) + '\t' + str(dict_species[u'common_name']) + '\t' + str(dict_species[u'assembly']) + '\t' + the_groups + '\t' + str(dict_species[u'taxon_id']) + '\t'+ str(dict_species[u'release']) + '\t' + the_alias
    
        f.write(file_content + '\n')
    
    f.close()
    
    print "; Job done, Job name :", outfile, time.strftime("%Y-%m-%d_%Hh%M")
