import threading
import logging
import subprocess
import pycountry
import gnupg
import obelisk
import json
import random
import time
import urllib2
from bitcoin import (
    apply_multisignatures,
    mk_multisig_script,
    mktx,
    multisign,
    scriptaddr
)
from tornado import iostream
import tornado.websocket
from twisted.internet import reactor
from node import constants, protocol, trust
from node.backuptool import BackupTool, Backup, BackupJSONEncoder
import bitcoin


class ProtocolHandler(object):
    def __init__(self, transport, market_application, handler, db_connection,
                 loop_instance):
        self.market_application = market_application
        self.market = self.market_application.market
        self.transport = transport
        self.handler = handler
        self.db_connection = db_connection

        self.transport.set_websocket_handler(self)

        self.all_messages = (
            'peer',
            'page',
            'peer_remove',
            'node_page',
            'listing_results',
            'listing_result',
            'no_listing_result',
            'release_funds_tx',
            'all'
        )

        # register on transport events to forward..
        self.transport.add_callbacks([
            (
                msg,
                {
                    'cb': getattr(self, 'on_%s' % msg),
                    'validator_cb': getattr(self, 'validate_on_%s' % msg)
                }
            )
            for msg in self.all_messages
        ])

        # handlers from events coming from websocket, we shouldnt need this
        self._handlers = {
            "load_page": self.client_load_page,
            "connect": self.client_connect,