import fcntl, socket, struct
import requests
import thread
import json
import time

from coapthon import defines
from coapthon.client.helperclient import HelperClient
from coapthon.utils import parse_uri

#import os
from config import Config




IDLE = 0
NEW_INTERACTION = 1
FAILED_TO_SEND = 2
SENT_SUCCESSFULLY = 3

class Live_coAP:

    def __init__(self,mac_address):
        print ("loaded live coAP")
        self.mac_address = mac_address
        self.lastTag = ''
        self.mode = ''
        self.time = ''
        self.liveState = IDLE
        self.proxy_uri = None

        # 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']


        #force local values for now
        #self.domain = "coap://192.168.0.199:5683"
        #self.endpoint = "/advanced"

        self.domain = "coap://coap.beamian.com:5683"
        self.endpoint = "/api/live-interactions"
        # 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 dump:')
        txString=json.dumps(data)
        print(txString)

        try:
            host, port, path = parse_uri(self.url)
            try:
                tmp = socket.gethostbyname(host)
                host = tmp
            except socket.gaierror:
                print ('socket.gaierror')
            
            client = HelperClient(server=(host, port))
            response = client.post(path, txString)
            print (response.pretty_print())
            client.stop()
            if response == None:
                print("No Response")
                self.liveState = FAILED_TO_SEND
                return False, 'Saved in device'
            else:
                if response.type == defines.Types['ACK']:
                    print("received ACK")
                    self.liveState = SENT_SUCCESSFULLY
                    print ('valid post created new interaction')
                    return True, 'Sent to server'

                elif response.type == defines.Types['CON']:
                    print("received CON")
                    self.liveState = SENT_SUCCESSFULLY
                    print ('valid post created new interaction')
                    return True, 'Sent to server'

                elif response.type == defines.Types['NON']:
                    print("received NON")
                    self.liveState = FAILED_TO_SEND
                    return False, 'Saved in device'

                else:
                    print("other")
                    self.liveState = FAILED_TO_SEND
                    return False, 'Saved in device'
            #self.liveState = SENT_SUCCESSFULLY
            #client.stop()
            #print ('valid post created new interaction')
            #return True, 'Sent to server'
            # 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:]


if __name__ == '__main__':  # pragma: no cover
    main()