#!/usr/bin/env python
"""
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
  This file is part of the Smart Developer Hub Project:
    http://www.smartdeveloperhub.org

  Center for Open Middleware
        http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
  Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
"""

__author__ = 'Fernando Serena'

from agora.client.agora import Agora
from blessings import Terminal
from rdflib import Graph
from time import time
import click
from requests import ConnectionError

total_derefs = 0
total_triples = 0


def stringify_uri_list(objs):
    if not len(objs):
        return '[]'
    return ', '.join(map(lambda x: x.n3(graph.namespace_manager), objs))


def out_load(uri, triples):
    global total_derefs
    global total_triples
    total_derefs += 1
    total_triples += len(triples)
    mto = ''
    if len(triples) > 1:
        mto = 's'
    print term.cyan + 'Deref' + '(<{}>) => {} triple{}'.format(uri, len(triples), mto) + term.normal


def out_seeds(seeds):
    pass
    # print seeds


def out_plink(uri, objs, sp):
    print term.green + '({}) Looking for triples with property {} at {}'.\
        format(sp, uri.n3(graph.namespace_manager), stringify_uri_list(objs)) + term.normal


def out_link(uri, objs, sp):
    print term.green + '({}) Following {} from {}'.\
        format(sp, uri.n3(graph.namespace_manager), stringify_uri_list(objs)) + term.normal


def out_type(uri, objs, sp):
    print term.green + "({}) Searching {}'s at {}".\
        format(sp, uri.n3(graph.namespace_manager), stringify_uri_list(objs)) + term.normal


def out_type_validation((_, s, p, o)):
    print term.green + 'Extracted {} as subject of type {}'.format(s.n3(graph.namespace_manager),
                                                                   o.n3(graph.namespace_manager)) + term.white


def out_tree(node):
    print term.bold_blue("Starting tree navigation {}".format(node.n3(graph.namespace_manager)))

term = Terminal()
graph = Graph()
print term.bold + term.underline + 'Agora Console Client v0.2' + term.normal

@click.command()
@click.option('--host', default='http://localhost:9001', help='URL of the Agora service.')
@click.option('--gp', default='{}', help='The graph pattern of your required fragment.')
@click.option('--u', is_flag=True, help='Unnatended plan execution.')
def get_fragment(host, gp, u):
    agora = Agora(host)

    print 'Trying to retrieve a fragment for:',
    print term.bold + gp + term.normal
    raw_input(term.bold_blue('(send)'))
    print 'Requesting a plan...',
    start_time = time()

    try:
        fragment, namespaces, plan = agora.get_fragment_generator(gp, on_load=out_load, on_seeds=out_seeds,
                                                                  on_plink=out_plink, on_link=out_link,
                                                                  on_type=out_type, on_type_validation=out_type_validation,
                                                                  on_tree=out_tree)
    except ConnectionError, e:
        print term.red + "\nCouldn't connect to {} due to:\n{}".format(host, e.message) + term.normal
        return

    print 'Done! (in ~{}ms)'.format(int(1000 * (time() - start_time)))
    raw_input(term.bold_blue('(take a look)'))
    print term.bold_yellow('Search plan:')
    print term.yellow + plan.serialize(format='turtle') + term.normal

    for (prefix, uri) in namespaces:
        graph.bind(prefix, uri)

    raw_input(term.blink(term.bold_blue('(run)')))

    final_triples = 0
    for _, s, p, o in fragment:
        graph.add((s, p, o))
        final_triples += 1
        print term.bold_green_on_bright_green('{} {} {} .'.format(s.n3(graph.namespace_manager),
                                                                  p.n3(graph.namespace_manager),
                                                                  o.n3(graph.namespace_manager)))
        if not u:
            raw_input(term.bold_blue('(more)'))

    print term.bold_yellow('\nFragment:')
    print term.yellow(graph.serialize(format='turtle'))

    print term.bold_white('Summary:')
    print 'Resources dereferenced = {}'.format(term.bold(str(total_derefs)))
    print 'Triples collected = {}'.format(term.bold(str(total_triples)))
    print 'Fragment triples = {}'.format(term.bold(str(final_triples)))

if __name__ == '__main__':
    get_fragment()
