import json
from MyUtils.HttpUtil import *


class MetadataWebUtil(object):
    def __init__(self, url):
        self.url = url

    def get_hbase(self, params):
        params = json.dumps(params)
        word = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.persagy.com/" xmlns:ent="http://entity.persagy.com">' \
               '<soapenv:Header/>' \
               '<soapenv:Body><ser:Query>' \
               '<arg0>%s</arg0>' \
               '</ser:Query></soapenv:Body></soapenv:Envelope>' % (params)
        res = HttpUtil.post(self.url, word)
        res = res.split("<return>")[1].split("</return>")[0]
        res = json.loads(res.replace("&#xd;", ""))
        return res

    def database_list(self):
        params = {
            "QueryType": "database_list"
        }
        res = self.get_hbase(params)
        return res["Content"]

    def table_list(self, database):
        params = {
            "QueryType": "table_list_strict",
            "Database": database
        }
        table_list_strict = self.get_hbase(params)["Content"]
        params = {
            "QueryType": "table_list",
            "Database": database
        }
        table_list = self.get_hbase(params)["Content"]
        table_list = [i for i in table_list if i not in table_list_strict]
        tables = {}
        for table in table_list_strict:
            childs = []
            for i in table_list:
                if i.startswith(table + "_"):
                    try:
                        word = i[len(table + "_"):]
                        if len(word) == 4 or len(word) == 6:
                            word = int(word)
                            childs.append(i)
                    except:
                        pass
            tables[table] = childs
        return tables
