#coding:utf-8
import os
import sys
import sunhpc
import socket
import sunhpc.commands
import sunhpc.db.helper

class Application(object):
    def __init__(self, argv=None):

        self.db     = None
        self.newdb  = None

    def connect(self):
        self.newdb = sunhpc.db.helper.DatabaseHelper()
        self.newdb.connect()

        self.db = sunhpc.commands.DatabaseConnection(self.newdb)
        return 1

    def search(self, command):
        return self.db.search(command)

    def execute(self, command):
        return self.db.execute(command)

    def fetchone(self):
        return self.db.fetchone()

    def fetchall(self):
        return self.db.fetchall()

    def getHostAttr(self, host, attr):
        return self.getHostAttrs(host).get(attr)

    def getHostAttrs(self, host):
        return self.db.getHostAttrs(host)

    def close(self):
        self.db.database.close()

    def commit(self):
        self.db.database.commit()

    def getNodeId(self, host):

        try:
            return int(host)
        except Exception:
            pass

        self.execute('select id from nodes where name="%s"' % host)
        try:
            nodeid, = self.fetchone()
            return nodeid
        except TypeError:
            nodeid = None

        self.execute('select max(n.id) from networks net, \
                        nodes n where net.ip="%s" and net.node=n.id' % host)
        try:
            nodeid, = self.fetchone()
            if nodeid:
                return nodeid
        except TypeError:
            nodeid = None

        self.execute('select max(n.id) from networks net, \
                        nodes n where net.mac="%s" and net.node=n.id' % host)
        try:
            nodeid, = self.fetchone()
            if nodeid:
                return nodeid
        except TypeError:
            nodeid = None

        return nodeid

    def __repr__(self):
        return 'SQLApplication'

class InsertEthersPlugin:
    """Base class for any module that wants to be notified when a node
    is added or deleted in the cluster"""

    def __init__(self, app):
        self.app = app
        self.screen = app.insertor.screen

    def update(self):
        "Regenerate your config files and reload them."
        pass

    def done(self):
        """Called just before insert-ethers quits and nodes
        have been added or removed."""
        pass

    def added(self, nodename):
        """This node has been added to the cluster."""
        pass

    def removed(self, nodename):
        "This node has been removed from the cluster"
        pass

    def changed(self, old, new):
        "Not currently used"
        pass
