import re
import os

import simplejson as json
import ordereddict

import aps2.uLogging
import aps2.utils


SUFFIX_SCHEMA = '.schema'


class Schema(object):
    def __init__(self, schema, controller_client):
        self.schema = schema
        self.list_schema = []
        for impl in schema[0].get("implements", []):
            self.list_schema.append(Schema(controller_client.get_type(impl), controller_client))


def get_schema(name, controller_client):
    dir_schemas = os.environ['APP_PATH'] + 'schemas/'
    if not os.path.exists(dir_schemas):
        os.makedirs(dir_schemas)
    nf_schema = name + SUFFIX_SCHEMA
    if os.path.isfile(dir_schemas + nf_schema):
        with open(dir_schemas + nf_schema) as infile:
            schema = json.loads(infile.read(), object_pairs_hook=ordereddict.OrderedDict)
    else:
        schema = controller_client.get_type(controller_client.list_services[name]["type"])
        with open(dir_schemas + nf_schema, 'wb') as outfile:
            outfile.write('%s' % schema)
    return Schema(schema, controller_client)


class Service(object):
    def __init__(self, controller_client, parsed_environ):
        aps2.uLogging.debug("__init__ in Service in service2")

        self.name = aps2.utils.find_name_service(parsed_environ.get("PATH_INFO"), controller_client.list_services)
        self.tree_schemas = get_schema(self.name, controller_client)
