# V2 adding stock Krian
# V3 adding offline stock retrieval (excel and stock Krian)

from __future__ import print_function
#import xlwings as xw
import time
import json
import datetime
import socket, threading, sys
import pywintypes
#from pdfstock import checkpdfstock
#import pdfstock
import importlib
from iteminventorydasa import QBStock
#from itemreportquery import QBStock
from random import randint

i=0
init = {'packinglistfilename' : '', 'bind' : '0.0.0.0', 'port' : 9999}
print('Starting')
try:
	
	filename = sys.argv[0][:sys.argv[0].find('.py')] + '.ini'
	print ("opening {}".format(filename))

	
	
	with open(filename) as fp:
		for line in fp:
			splitline = line.split('=')
			if splitline[0] in init:
				init[splitline[0]] = splitline[1][:splitline[1].find('#')]
except:
	print ("Error Opening {}".format(filename))

print ("trying to open {}".format(init['packinglistfilename']))
	


def convertfloatnoltoint(stock):
	if isinstance(stock, (float, int)):
		return int(stock)
	elif stock == "Nol":
		return 0
	elif stock is None:
		return 0
	else:
		return 0








def searchStockQB(client_socket=None, filename='', searchitems = {}):
	#return searchitems
	searchitemsRt = {}
	#searchitemsRt['month'] = monthstock
	print(f"searchStockQB -> {searchitems} = Received Request: {searchitems}")
	itemInvDict = QBStock(searchitems = searchitems)
	print(f"searchStockQB -> {searchitems} = Received Request: {itemInvDict}")
	for searchitem in searchitems:
		print (f"searchStockQB -> searachitem: {searchitem}")
		searchitem= searchitem.strip('"')
		if searchitem in itemInvDict:
			#print (itemInvDict[searchitem][0])
			searchitemsRt[itemInvDict[searchitem][0]] = itemInvDict[searchitem][1]
		else:
			searchitemsRt[searchitem] = "N/A"
	
	print (f"searchStockQB -> The Return: {searchitemsRt}")
	print ("")
	#print(datetime.datetime.now())
	#runningTime = datetime.datetime.now()-stime
	#print("Finish in: {}.{} sec".format(runningTime.seconds, runningTime.microseconds)) 
	
	if client_socket != None:
		data_string = json.dumps(searchitemsRt)
		data_string = data_string.encode()
		#client_socket.send(json.dumps(searchitemsRt))
		client_socket.send(data_string)
		client_socket.close()
		
	return searchitemsRt

if __name__=='__main__':
	print(init['bind'], init['port'])
	bind_ip = init['bind'] #'0.0.0.0'
	bind_port = 9999 #init['port'] #9999
	try:
		server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		server.bind((bind_ip, bind_port))
		server.listen(5)  # max backlog of connections

		print ('Listening on {}:{}'.format(bind_ip, bind_port))
	except Exception as error:
		print (error)
		sys.exit()



def is_json(myjson):
	try:
		json_object = json.loads(myjson)
		json_object = None
	except ValueError as e:
		return False
	return True
  

def handle_offline_request(client_socket, lists):
	try:
		buffer = 4096
		data_string=lists
		data_string = json.dumps(lists)
		size = len(data_string)
		sSize = "Size {}".format(size)
		sSize = sSize.encode()
		print("Size to be send:{}; data_string:{}".format(sSize, size))
		client_socket.send(sSize)
		request = client_socket.recv(buffer)
		request = request.decode()
		#print ('Received:{}'.format(request))
		if request.startswith('Got Size'):
			data_string = data_string.encode()
			client_socket.sendall(data_string)
			request = client_socket.recv(buffer)
			request = request.decode()
			print ('Received:{}'.format(request))
			if request.startswith('Got All Data'):
				sBye = "Bye"
				sBye = sBye.encode()
				client_socket.send(sBye)
	except:
		print("handle_offline_request Error")
	finally:
		client_socket.close

if __name__ == '__main__':
    #xyz={"TH-001aa":"","ECO-016":"","th-002":"","ECO:0:ECO-002":""}
    xyz={"ECO:0:ECO-002":"","TIERO:R, WY, SU, CM, DM, TR, TM:TI-X-0095-DM":""}
    # xyz={'"TIERO:R, WY, SU, CM, DM, TR, TM:TI-X-0095-DM"':''}
    print ("searchitems", xyz)
    responseRt = searchStockQB(searchitems=xyz)
    print(responseRt)


    while i<2:
        i=0
        #sys.exit() to cut not going to start listening
        client_sock, address = server.accept()
        print("")
        print("")
        print (datetime.datetime.now(), 'Accepted connection from {}:{}'.format(address[0], address[1]))
        request = client_sock.recv(4096)
        request = request.decode()
        print("request:", type(request), request)
        if is_json(request):
            print("json:{}".format(request))
            abc = json.loads(request)
            print(type(abc), abc)
            responseRt = searchStockQB(searchitems=abc)
            responseRt = json.dumps(responseRt)
            responseRt = responseRt.encode()
            client_sock.send(responseRt)
            client_sock.close()
        elif request.lower() == 'request':
            #print ("replied request")
            dataoffline = getofflineStock(filename=init['packinglistfilename'])
            handle_offline_request(client_sock, dataoffline)
            # client_sock.send("hi".encode())
            # client_sock.close()
        else:
            #print("else")
            client_sock.send(b'Bye')
            client_sock.close()
        print(datetime.datetime.now(), "Connection closed")

