import fcntl, socket, struct
import requests
import thread
import json
import time
#import os
from config import Config

IDLE = 0
NEW_INTERACTION = 1
FAILED_TO_SEND = 2
SENT_SUCCESSFULLY = 3

class Live:

    def __init__(self,mac_address):

        self.mac_address = mac_address
        self.lastTag = ''
        self.mode = ''
        self.time = ''
        self.liveState = IDLE


        # set default domain, endpint token
        self.domain = ''
        self.endpoint = ''
        self.token = ''

        # update with new configuration if xml exist and is valid
        config = Config().getLive()
        if config is not None:
            self.domain = config['domain']
            self.endpoint = config['endpoint']
            self.token = config['token']

        # Read last tag and mode (standard,etc) from log file
        #self.lastTag = '04528A22A44080'  # testing only
        #self.mode = 'standard' # testing only



    @property
    def url(self):
        return self.domain + self.endpoint

	# Write a a line for wifi transmission
    def sendLineLive(self, tag, timeStr, id, ctype):
        self.liveState = NEW_INTERACTION
        self.lastTag = tag
        self.mode = ctype
        #self.mode = 'referencetest'
        #self.lastTag = '04528A22A44080'
        #self.mac_address= 'b8:27:eb:c2:b2:c4'
        thread.start_new_thread(self.sendLast,())
        #self.sendLast()

    def getLiveState(self):
        return self.liveState

    def resendLastInteraction(self):
        thread.start_new_thread(self.sendLast,())

    def sendLast(self):

        # test if there is any valid log line to send and load it
        data = {
            'mac_address': self.mac_address.lower(),
            'tag_id': self.lastTag.upper(),
            'mode': self.mode
        }

        #print ('posting ')
        print (data)
        print (' to url ' + self.url)
        #print json.dumps(data, indent=4)
        try:
            response = requests.post(self.url, json=data)
            print ('response')
            print response
            if response.status_code == 201:
                # valid post - created new interaction
                print ('valid post created new interaction')
                self.liveState = SENT_SUCCESSFULLY
                return True, 'Sent to server'
            if response.status_code == 200:
                # valid post - update interaction timestap
                print ('valid post - update interaction timestamp')
                self.liveState = SENT_SUCCESSFULLY
                return True, 'Already in server'
            #print ('invalid post - some error')
            self.liveState = FAILED_TO_SEND
            return False, 'Saved in device'

        except Exception, e:
            errorMsg = str(e)
            self.liveState = FAILED_TO_SEND
            #print 'Live interaction Exception: ', errorMsg
            return False, errorMsg[errorMsg.find("]") + 1:]
