#! /usr/bin/env python
# __author__ = "Parisa Kianmajd"
#__version__ = "1.0.1"
# input: a text file in CleanTax format
# output: a csv file with three columns <Name, Author, Rank>

# Copyright (c) 2014 University of California, Davis
# 
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import sys
import csv
import itertools
import wizardParser


def findRank(e):
    if len(e.split("_")) == 3:
           return "Subspecies"
    if len(e.split("_")) == 2:
        return "Species"
    if len(e.split("_")) == 1:
        if e.endswith("ini"):
            return "Tribe"
        elif e.endswith("inae"):
            return "Subfamily"
        elif e.endswith("idae"):
            return "Family"
        elif e.endswith("oidea"):
            return "Superfamily"
        else:
            return "Genus"
    return "Undefined"

def main(iFile):
    outData = []
    inputData = []
    isaDict = {}
    for n in iFile:
        inputData += open(n).readlines() 
    for line in inputData:
        if line.startswith("taxonomy"):
            author = line.split(" ")[1]
            isa = {}
        if line.startswith("("):
            elements = line[1:-2]. strip(")").split(" ")
            isa.update({elements[0] : elements[1:]})
            for e in elements:
                rank = findRank(e)
                outData.append([e, author, rank])
        if line == "\n":
            isaDict.update({author: isa})
        if line.startswith("articulation"):
            exit
    outData.sort()
    outData = list(outData for outData,_ in itertools.groupby(outData))
    with sys.stdout as oFile:
            writer = csv.writer(oFile)
            writer.writerow(["Name", "Author", "Rank"])
            for d in outData:
                writer.writerow(d)
    for a in isaDict:
        with open(a + "_isa" + ".csv",  'w+') as isaFile:
            writer = csv.writer(isaFile)
            writer.writerow(["Name1", "Relation", "Name2"])
            for p in isaDict[a]:
                for c in isaDict[a][p]:
                    writer.writerow([c, "ISA", p])

# MAIN
if __name__ == '__main__':
    main(wizardParser.args.iFile)
