import os
import requests
import logging
import sys
import json
from lxml import etree as ElementTree

requests.packages.urllib3.disable_warnings()

class BioTools(object):

    def __init__(self, registerUrl="https://bio.tools/api"):
        self.registerUrl = registerUrl
        pass

    def get_resource(self, options):
        '''
        Gets a resource object with resource name

        :params options: act = action (delete, get, register, update)
                         resname = resource name (optional)
                         resFile = XML resource file path (if resname not provided)
        :type options: object
        :return: dict
        '''
        ressource={}
        if (options.act=="delete" or options.act=="get" )and options.resname!=None:
            ressource['name']=options.resname
        else:
            descFile = open(options.resFile, "r")
            desc=descFile.read()
            descFile.close()

            if desc==None or len(desc)<1:
                raise Exception("descriptor file %s not usable "% ( options.resFile) );
            else:
                ressource= dict()
                if options.xmlTransportFormat==True:
                    parser = ElementTree.XMLParser(recover=True)
                    tree = ElementTree.fromstring(desc, parser)
                    dtree=self.treeToDict(tree)
                    ressource['name']=dtree['resources'][ 'resource']['name']
                else:
                    ddict=json.loads(desc)
                    ressource['name']=ddict['name']

                if 'name' in list(ressource.keys()):
                    if options.verbose:
                        logging.info("Going to manage ressource with name ***%s***" %(ressource['name']))
                else:
                    raise Exception("no attribute name in json object (file %s )"% ( options.resFile) );
        return ressource

    def treeToDict(self, t):
        d = {t.tag: {} if t.attrib else None}
        childr = list(t)
        if childr:
            dd = defaultdict(list)
            for dc in map(self.treeToDict, childr):
                for k, v in dc.iteritems():
                    dd[k].append(v)
            d = {t.tag: {k:v[0] if len(v) == 1 else v for k, v in dd.iteritems()}}
        if t.attrib:
            d[t.tag].update(('@' + k, v) for k, v in t.attrib.iteritems())
        if t.text:
            text = t.text.strip()
            if childr or t.attrib:
                if text:
                  d[t.tag]['#text'] = text
            else:
                d[t.tag] = text
        return d


    def execLoginCmd(self, username, password):
        r = requests.post(self.registerUrl+"/auth/login", verify=False, data={'username': username, 'password': password})
        status = r.status_code
        if status != 200:
            raise Exception('Login failure: '+r.json())
        return r.json()

    def execRegisterOrUpdateCmd(self, token, resFile, transportFormat):
        headers = {'Authorization': 'Token '+str(token), 'Accept': transportFormat}
        regfile = {'file': (resFile, open(resFile, 'rb'), 'application/xml', {'Expires': '0'})}
        r = requests.post(self.registerUrl+"/tool", headers=headers, verify=False,
                          files=regFile)
        status = r.status_code
        if status != 200:
            raise Exception('RegisterOrUpdate failure: '+r.json())
        return r.json()

    def execDeleteCmd(self, token, affiliation, name):
        headers = {'Authorization': 'Token '+str(token)}
        r = requests.delete(self.registerUrl+"/tool"+"/"+affiliation+"/"+name,
                            verify=False, headers=headers)
        status = r.status_code
        if status != 200:
            raise Exception('RegisterOrUpdate failure: '+r.json())
        return r.json()

    def execGetCmd(self, affiliation, name,transportFormat):
        headers = {'Accept': transportFormat}
        r = requests.get(self.registerUrl+"/tool"+"/"+affiliation+"/"+name,
                         verify=False, headers=headers)
        status = r.status_code
        if status != 200:
            raise Exception('RegisterOrUpdate failure: '+r.json())
        return r.json()

@@ -94,16 +94,52 @@
 mentTree
+%0Afrom collections import defaultdict
 %0A%0Areques
@@ -2889,39 +2889,42 @@
 ogin failure: '+
-r.json(
+str(status
 ))%0A        retur
@@ -3102,17 +3102,17 @@
      reg
-f
+F
 ile = %7B'
@@ -3417,39 +3417,164 @@
 date failure: '+
-r.json(
+str(status))%0A        res = %7B%7D%0A        try:%0A            res = r.json()%0A        except Exception as e:%0A            logging.debug(str(e
 ))%0A        retur
@@ -3568,39 +3568,34 @@
         return r
-.json()
+es
 %0A%0A    def execDe
@@ -3936,39 +3936,164 @@
 date failure: '+
-r.json(
+str(status))%0A        res = %7B%7D%0A        try:%0A            res = r.json()%0A        except Exception as e:%0A            logging.debug(str(e
 ))%0A        retur
@@ -4087,39 +4087,34 @@
         return r
-.json()
+es
 %0A%0A    def execGe
@@ -4452,23 +4452,26 @@
 lure: '+
-r.json(
+str(status
 ))%0A     

fix error management