# -*- coding: utf-8 -*-
# Open Source Initiative OSI - The MIT License (MIT):Licensing
#
# The MIT License (MIT)
# Copyright (c) 2012 DotCloud Inc (opensource@dotcloud.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


from nose.tools import assert_raises
import gevent
import gevent.local
import random
import md5

from zerorpc import zmq
import zerorpc
from testutils import teardown, random_ipc_endpoint


def test_resolve_endpoint():
    test_endpoint = random_ipc_endpoint()
    c = zerorpc.Context()

    def resolve(endpoint):
        if endpoint == 'titi':
            return test_endpoint
        return endpoint

    cnt = c.register_middleware({
        'resolve_endpoint': resolve
        })
    print 'registered_count:', cnt
    assert cnt == 1

    print 'resolve titi:', c.hook_resolve_endpoint('titi')
    assert c.hook_resolve_endpoint('titi') == test_endpoint

    print 'resolve toto:', c.hook_resolve_endpoint('toto')
    assert c.hook_resolve_endpoint('toto') == 'toto'

    class Resolver():

        def resolve_endpoint(self, endpoint):
            if endpoint == 'toto':
                return test_endpoint
            return endpoint

    cnt = c.register_middleware(Resolver())
    print 'registered_count:', cnt
    assert cnt == 1

    print 'resolve titi:', c.hook_resolve_endpoint('titi')
    assert c.hook_resolve_endpoint('titi') == test_endpoint
    print 'resolve toto:', c.hook_resolve_endpoint('toto')
    assert c.hook_resolve_endpoint('toto') == test_endpoint

    c2 = zerorpc.Context()
    print 'resolve titi:', c2.hook_resolve_endpoint('titi')
    assert c2.hook_resolve_endpoint('titi') == 'titi'
    print 'resolve toto:', c2.hook_resolve_endpoint('toto')
    assert c2.hook_resolve_endpoint('toto') == 'toto'


def test_resolve_endpoint_events():
    test_endpoint = random_ipc_endpoint()
    c = zerorpc.Context()

    class Resolver():
        def resolve_endpoint(self, endpoint):
            if endpoint == 'some_service':
                return test_endpoint
            return endpoint

    class Srv(zerorpc.Server):
        def hello(self):
            print 'heee'
            return 'world'

    srv = Srv(heartbeat=1, context=c)
    with assert_raises(zmq.ZMQError):
        srv.bind('some_service')

    cnt = c.register_middleware(Resolver())
    assert cnt == 1
    srv.bind('some_service')
    gevent.spawn(srv.run)

    client = zerorpc.Client(heartbeat=1, context=c)
    client.connect('some_service')
    assert client.hello() == 'world'

    client.close()
    srv.close()


class Tracer:
    '''Used by test_task_context_* tests'''
    def __init__(self, identity):
        self._identity = identity
        self._locals = gevent.local.local()
        self._log = []

    @property
    def trace_id(self):
        return self._locals.__dict__.get('trace_id', None)

    def load_task_context(self, event_header):
        self._locals.trace_id = event_header.get('trace_id', None)
        print self._identity, 'load_task_context', self.trace_id
        self._log.append(('load', self.trace_id))

    def get_task_context(self):
        if self.trace_id is None:
            # just an ugly code to generate a beautiful little hash.
            self._locals.trace_id = '<{0}>'.format(md5.md5(
                    str(random.random())[3:]
                    ).hexdigest()[0:6].upper())
            print self._identity, 'get_task_context! [make a new one]', self.trace_id
            self._log.append(('new', self.trace_id))
        else:
            print self._identity, 'get_task_context! [reuse]', self.trace_id
            self._log.append(('reuse', self.trace_id))
        return { 'trace_id': self.trace_id }


def test_task_context():
    endpoint = random_ipc_endpoint()
    srv_ctx = zerorpc.Context()
    cli_ctx = zerorpc.Context()

    srv_tracer = Tracer('[server]')
    srv_ctx.register_middleware(srv_tracer)
    cli_tracer = Tracer('[client]')
    cli_ctx.register_middleware(cli_tracer)

    class Srv:
        def echo(self, msg):
            return msg

        @zerorpc.stream
        def stream(self):
            yield 42

    srv = zerorpc.Server(Srv(), context=srv_ctx)
    srv.bind(endpoint)
    srv_task = gevent.spawn(srv.run)

    c = zerorpc.Client(context=cli_ctx)
    c.connect(endpoint)

    assert c.echo('hello') == 'hello'
    for x in c.stream():
        assert x == 42

    srv.stop()
    srv_task.join()

    assert cli_tracer._log == [
            ('new', cli_tracer.trace_id),
            ('reuse', cli_tracer.trace_id),
            ]
    assert srv_tracer._log == [
            ('load', cli_tracer.trace_id),
            ('reuse', cli_tracer.trace_id),
            ('load', cli_tracer.trace_id),
            ('reuse', cli_tracer.trace_id),
            ]

def test_task_context_relay():
    endpoint1 = random_ipc_endpoint()