import xml.etree.ElementTree as ET
import win32com.client
import xmltodict
import pprint
import datetime
import pandas as pd
from datetime import date
import timeit

class UnitOfMeasureSetQuery:
    def __init__(self,  **kwargs) -> None:
        # print(f'kwargs:{kwargs}')
        # print(args)
        # self.PurchaseOrderList=[]
        self.PurchaseOrderList= kwargs['PurchaseOrderList'] if 'PurchaseOrderList' in kwargs else []
        self.RefNumber = kwargs['RefNumber'] if 'RefNumber' in kwargs else None
        self.PurchaseOrderType = kwargs['PurchaseOrderType'] if 'PurchaseOrderType' in kwargs else 'SalesByCustomerSummary'
        self.IncludeLineItems = kwargs['IncludeLineItems'] if 'IncludeLineItems' in kwargs else 'False'
        self.TxnDateRangeFilter = kwargs['TxnDateRangeFilter'] if 'TxnDateRangeFilter' in kwargs else None
        self.DateMacro = None
        if 'DateMacro' in kwargs:
            if kwargs['DateMacro'] in ['All', 'Today', 'ThisWeek', 'ThisWeekToDate', 'ThisMonth', 'ThisMonthToDate', 'ThisQuarter', 'ThisQuarterToDate', 'ThisYear', 'ThisYearToDate', 'Yesterday', 'LastWeek', 'LastWeekToDate', 'LastMonth', 'LastMonthToDate', 'LastQuarter', 'LastQuarterToDate', 'LastYear', 'LastYearToDate', 'NextWeek', 'NextFourWeeks', 'NextMonth', 'NextQuarter', 'NextYear']:
                self.DateMacro = kwargs['DateMacro']
        self.FromTxnDate =  self.validate_date(kwargs['FromTxnDate']) if 'FromTxnDate' in kwargs else None
        self.ToTxnDate = self.validate_date(kwargs['ToTxnDate']) if 'ToTxnDate' in kwargs else None
        self.ReportEntityFilter = kwargs['ReportEntityFilter'] if 'ReportEntityFilter' in kwargs else None
        self.FullName = kwargs['FullName'] if 'FullName' in kwargs else None
        # print(self.DateMacro, self.TxnDateRangeFilter, self.FromTxnDate, self.ToTxnDate)
    def create_sub_element(self, ET, parentNode, thisNode, text="\n", whiteSpace = 0, attrib =None):
        if type(attrib) is not dict:
            attrib = {}
        ele = ET.SubElement(parentNode, thisNode)
        for x in attrib:
            ele.set(x, attrib[x])
        ele.text = text
        tail = "\n"
        for x in range(whiteSpace):
            tail = tail + " "
        ele.tail = tail
        return ele

    def create_QBXML(self):
        root = ET.Element("QBXML")
        root.tail = "\n"
        root.text = "\n  "
        QBXMLMsgsRq = ET.SubElement(root, "QBXMLMsgsRq")
        # QBXMLMsgsRq.set("onError", "continueOnError")
        QBXMLMsgsRq.set("onError", "stopOnError")
        QBXMLMsgsRq.tail = "\n"
        QBXMLMsgsRq.text = "\n    "
        UnitOfMeasureSetQueryRq = self.create_sub_element(ET, QBXMLMsgsRq, "UnitOfMeasureSetQueryRq","\n      " )
        FullName = self.create_sub_element(ET, UnitOfMeasureSetQueryRq, "FullName", "Box of 12")
        # NameFilter = self.create_sub_element(ET, UnitOfMeasureSetQueryRq, "NameFilter")
        # MatchCriterion = self.create_sub_element(ET, NameFilter, "MatchCriterion", "StartsWith")
        # Name = self.create_sub_element(ET, NameFilter, "Name", "Box of 12")
		
        mydata = ET.tostring(root, encoding = "unicode")

        qbxml_query = """<?xml version="1.0" encoding="utf-8"?>\n"""
        qbxml_query = qbxml_query + """<?qbxml version="13.0"?>"""
        qbxml_query = qbxml_query + "\n" + mydata
        print(qbxml_query)
        
        self.getConvertionRatio(self.connect_to_quickbooks(qbxml_query))
        return qbxml_query

    def connect_to_quickbooks(self, qbxml_query):
        # Connect to Quickbooks
        # sessionManager = win32com.client.Dispatch("QBXMLRP2.RequestProcessor")
        # sessionManager.OpenConnection('', 'DASA')
        # enumfodnc= win32com.client.Dispatch('QBXMLRP2.RequestProcessor')
        # print(enumfodnc)
        # print(enumfodnc.qbFileOpenDoNotCare)
        sessionManager = win32com.client.Dispatch("QBXMLRP2.RequestProcessor")
        sessionManager.OpenConnection('', 'DASA2')
        # ticket = sessionManager.BeginSession("z:\\DBW Bogor.qbw", 2)

        ticket = sessionManager.BeginSession("", 2)

        # Send query and receive response
        response_string = sessionManager.ProcessRequest(ticket, qbxml_query)

        # Disconnect from Quickbooks
        sessionManager.EndSession(ticket)     # Close the company file
        sessionManager.CloseConnection()      # Close the connection
        print (response_string)
        return response_string

    def getConvertionRatio(self, response_string):
        QBXML = ET.fromstring(response_string)
        print(QBXML.findall('.//*[Name="Box"]/Name'))
        print(QBXML.findall('.//Name[.="Box"]')[0].tag)
        print(QBXML.findall('.//*[.="Box"]')[0].text)


        print(QBXML.findtext("Box"))

if __name__ == '__main__':

 
    starttime = timeit.default_timer()
    # ini=UnitOfMeasureSetQuery(DateMacro='ThisWeek', IncludeLineItems='true', RefNumber=["L2307-04429", "L2307-02992", 'L2307-03649',"L2307-02108", "L2307-03638"])
    ini=UnitOfMeasureSetQuery(DateMacro='ThisWeek', IncludeLineItems='true', RefNumber=["L2307-04429", "L2307-05899"])
    # ini=UnitOfMeasureSetQuery(DateMacro='ThisWeek', IncludeLineItems='true')
    # # ini=UnitOfMeasureSetQuery(DateMacro='LastWeek', IncludeLineItems='true')
    # print(ini.PurchaseOrderList)
    ret=ini.create_QBXML()
    print(ret)
	# print(ini.connect_to_quickbooks(ini.create_QBXML))
    # ini.getConvertionRatio(ret)
    print("The time difference is :", timeit.default_timer() - starttime)