#!/usr/bin/env python3

import dinemic
import logging
import os
import sys
import time
import urllib.request
import yaml

from starsheep.context import Context
from starsheep.scripts.script import Script
from starsheep.variables.variable import Variable
from starsheep.listeners.listener import Listener
from starsheep.models.model import Model


def get_url(path):
    p = path
    if path.startswith('/'):
        p = 'file://' + path
    elif path.startswith('./'):
        p = 'file://' + os.getcwd() + '/' + path

    logging.debug('Opening file from ' + p)
    return p


def check_version(document, context):
    logging.info('Loading application')
    if 'version' not in document:
        print('missing schema version')
        sys.exit(1)

    if str(document['version']) not in ['2020.02']:
        print('Unsupported version')
        sys.exit(1)

    f.close()


def load_application(document, context):
    logging.info('Loading application')

    if 'application' in document:
        if 'variables' in document['application']:
            context.variables.update(Variable.load(document['application']['variables'], context))

        if 'scripts' in document['application']:
            Script.load(document['application']['scripts'], context)

        if 'listeners' in document['application']:
            Listener.load(document['application']['listeners'], context)

        if 'models' in document['application']:
            Model.load(document['application']['models'], context)


def import_application(document, context):
    if 'import' in document:
        if type(document['import']) == str:
            f = urllib.request.urlopen(get_url(document['import'].decode('utf-8')))
            new_document = yaml.load(f)
            f.close()
            check_version(new_document)
            load_application(new_document, context)
        elif type(document['import']) == list:
            for i in document['import']:
                f = urllib.request.urlopen(get_url(i.decode('utf-8')))
                new_document = yaml.load(f)
                f.close()

                check_version(new_document)
                load_application(new_document, context)


def apply_data(document, context):
    logging.info('Loading data')

    if 'data' in document:
        for model in document['data'].keys():
            if type(document['data'][model]) == dict:
                Model.apply(model, document['data'][model], context)
            elif type(document['data'][model]) == list:
                for item in document['data'][model]:
                    Model.apply(model, item, context)
            else:
                raise Exception('Unknown type of model')


def import_data(document, context):
    if 'import' in document:
        if type(document['import']) == str:
            f = urllib.request.urlopen(get_url(document['import'].decode('utf-8')))
            new_document = yaml.load(f)
            f.close()

            check_version(new_document)
            load_data(new_document, context)
        elif type(document['import']) == list:
            for i in document['import']:
                f = urllib.request.urlopen(get_url(i.decode('utf-8')))
                new_document = yaml.load(f)
                f.close()

                check_version(new_document)
                load_data(new_document.decode('utf-8'), context)


if __name__ == "__main__":
    options = sys.argv[1:]

    if len(options) <= 0:
        print('Use ' + sys.argv[0] + ' [options] yaml_file')
        sys.exit(1)

    if '--verbose' in sys.argv:
        options.remove('--verbose')
        logging.basicConfig(level=logging.DEBUG)
        dinemic.set_loglevel('debug')
    if '--debug' in sys.argv:
        options.remove('--debug')
        logging.basicConfig(level=logging.INFO)
        dinemic.set_loglevel('info')
    else:
        logging.basicConfig(level=logging.ERROR)
        dinemic.set_loglevel('none')

    if '--no-data' in options:
        load_data = False
        options.remove('--no-data')
    else:
        load_data = True

    if '--launch' in options:
        launch = True
        options.remove('--launch')
    else:
        launch = False

    dinemic.prepare()

    ctx = Context()

    f = urllib.request.urlopen(get_url(options[-1]))
    document = yaml.load(f)
    f.close()

    check_version(document, ctx)
    import_application(document, ctx)
    load_application(document, ctx)
    import_data(document, ctx)

    if load_data:
        import_data(document, ctx)
        apply_data(document, ctx)

    # TODO: Add CRUD
    # TODO: Add launch mode

    if launch:
        logging.info('Starting launch mode')
        dinemic.launch()

        while True:
            time.sleep(1)
