import types
import traceback
import binascii
import threading
import time
import thread
import os
import struct
import sys
import textwrap
import re

class deviceBase():

    def __init__(self, name=None, number=None, mac=None, Q=None, mcu=None, companyId=None, offset=None, mqtt=None, Nodes=None):
        self.offset = offset
        self.company = companyId
        self.name = name
        self.number = number 
        self.q = Q
        self.deviceName = name + '_[' + mac +  ':' + number[0:2] + ':' + number[2:] + ']!'
        self.chName = "M1" + '_[' + mac + ':'
        self.chName2 = '_[' + mac + ':'
        print 'device name is:'
        print self.deviceName
        mac2 = mac.replace(":", "")
        self.mac = mac2.upper()
        self.address = 1
        self.debug = True
        self.mcu = mcu
        self.firstRun = True
        self.mqtt = mqtt
        self.nodes = Nodes
        #local dictionary of derived nodes ex: localNodes[tank_0199] = self
        self.localNodes = {}
        os.system("chmod 777 /root/reboot")
        os.system("echo nameserver 8.8.8.8 > /etc/resolv.conf")
        
        
    def sendtodbLoc(self, ch, channel, value, timestamp, deviceName, mac):


        #this will add your derived nodes the master nodes list, allowing them to receive sets!!
        localNodesName = deviceName + "_" + str(ch) + "99"

        if not self.localNodes.has_key(localNodesName):
            self.localNodes[localNodesName] = True
            self.nodes[localNodesName] = self

        #make the techname 
        lst = textwrap.wrap(str(mac), width=2)
        tech = ""
        for i in range(len(lst)):
            tech += lst[i].lower() + ":"
        

        chName2 = '_[' + tech 

        if int(ch) < 10:
            ch = "0" + str(int(ch))

        if len(ch) > 2:
            ch = ch[:-2]

        dname = deviceName + chName2 + str(ch) + ":98]!"

        csplit = re.split(r"(.*?)_\[(.*?)\]", dname)
        nodeTypeName = csplit[1]
        uniqueID = csplit[2]
        company = "194"

        if int(timestamp) == 0:
            timestamp = self.getTime()
        
        topic = 'meshify/db/%s/%s/%s/%s/%s' % (company, "_", nodeTypeName, uniqueID.lower(), channel)
        print topic
        msg = """[{"value":"%s"}]""" % (str(value))
        print msg
        self.q.put([topic, msg, 0])

    def sendtodbDevJSON(self, ch, channel, value, timestamp, deviceName):

        if int(ch) < 10:
            ch = "0" + str(int(ch))
        dname = deviceName + self.chName2 + str(ch) + ":99]!"
        if int(timestamp) == 0:
            timestamp = self.getTime()

        csplit = re.split(r"(.*?)_\[(.*?)\]", dname)
        nodeTypeName = csplit[1]
        uniqueID = csplit[2]
        company = "194"
        
        topic = 'meshify/db/%s/%s/%s/%s/%s' % (company, "_", nodeTypeName, uniqueID.lower(), channel)
        print topic
        msg = """[{"value":%s}]""" % (str(value))
        print msg
        self.q.put([topic, msg, 0])

    def sendtodbLora(self, ch, channel, value, timestamp, deviceName):

        if ":" not in ch:
            ch = ch[0:2] + ":" + ch[2:4]

        #this will add your derived nodes the master nodes list, allowing them to receive sets!!
        localNodesName = deviceName + "_" + str(ch).replace(':', "")

        if not self.localNodes.has_key(localNodesName):
            self.localNodes[localNodesName] = True
            self.nodes[localNodesName] = self

        

        dname = deviceName + self.chName2 + str(ch) + "]!"

        csplit = re.split(r"(.*?)_\[(.*?)\]", dname)
        nodeTypeName = csplit[1]
        uniqueID = csplit[2]
        company = "194"

        if int(timestamp) == 0:
            timestamp = self.getTime()
        
        topic = 'meshify/db/%s/%s/%s/%s/%s' % (company, "_", nodeTypeName, uniqueID.lower, channel)
        print topic
        msg = """[{"value":"%s"}]""" % (str(value))
        print msg
        self.q.put([topic, msg, 0])
        
    def sendtodbDev(self, ch, channel, value, timestamp, deviceName):


        #this will add your derived nodes the master nodes list, allowing them to receive sets!!
        localNodesName = deviceName + "_" + str(ch) + "99"

        if not self.localNodes.has_key(localNodesName):
            self.localNodes[localNodesName] = True
            self.nodes[localNodesName] = self

        if int(ch) < 10:
            ch = "0" + str(int(ch))

        dname = deviceName + self.chName2 + str(ch) + ":99]!"

        

        if int(timestamp) == 0:
            timestamp = self.getTime()

        csplit = re.split(r"(.*?)_\[(.*?)\]", dname)
        nodeTypeName = csplit[1]
        uniqueID = csplit[2]
        company = "194"
        
        topic = 'meshify/db/%s/%s/%s/%s/%s' % (company, "_", nodeTypeName, uniqueID.lower(), channel)
        print topic
        msg = """[{"value":"%s"}]""" % (str(value))
        print msg
        self.q.put([topic, msg, 0])
        
    def sendtodbCH(self, ch, channel, value, timestamp):


        if int(ch) < 10:
            ch = "0" + str(ch)

        dname = self.chName + str(ch) + ":99]!"

        

        if int(timestamp) == 0:
            timestamp = self.getTime()

        csplit = re.split(r"(.*?)_\[(.*?)\]", dname)
        nodeTypeName = csplit[1]
        uniqueID = csplit[2]
        company = "194"
        
        topic = 'meshify/db/%s/%s/%s/%s/%s' % (company, "_", nodeTypeName, uniqueID.lower(), channel)
        print topic
        msg = """[{"value":"%s"}]""" % (str(value))
        print msg
        self.q.put([topic, msg, 0])
    
    def sendtodb(self, channel, value, timestamp):

        if int(timestamp) == 0:
            timestamp = self.getTime()
            if timestamp < 1400499858:
                return
        else:
            timestamp =  str(int(timestamp) + int(self.offset))

        csplit = re.split(r"(.*?)_\[(.*?)\]", self.deviceName)
        nodeTypeName = csplit[1]
        uniqueID = csplit[2]
        company = "194"
        
        topic = 'meshify/db/%s/%s/%s/%s/%s' % (company, "_", nodeTypeName, uniqueID.lower(), channel)
        print topic
        msg = """[{"value":"%s"}]""" % (str(value))
        print msg
        self.q.put([topic, msg, 0])
    
    def sendtodbJSON(self, channel, value, timestamp):

        if int(timestamp) == 0:
            timestamp = self.getTime()
            if timestamp < 1400499858:
                return
        else:
            timestamp =  str(int(timestamp) + int(self.offset))
        
        csplit = re.split(r"(.*?)_\[(.*?)\]", self.deviceName)
        nodeTypeName = csplit[1]
        uniqueID = csplit[2]
        company = "194"
        
        topic = 'meshify/db/%s/%s/%s/%s/%s' % (company, "_", nodeTypeName, uniqueID.lower(), channel)
        print topic
        msg = """[{"value":%s}]""" % (str(value))
        print msg
        self.q.put([topic, msg, 0])
    def getTime(self):
        return str(int(time.time() + int(self.offset)))




