# importing modules
from tkinter import *
import tkinter.messagebox
import sqlite3
# class for Front End UI
class product:
    def __init__(self, root):
        p = Database()  #object reference instance  of Database class as p
        p.conn()
        #Code for creating the window
        self.root = root
        self.root.title("WAREHOUSE INVENTORY SALES AND PURCHASE MANAGMENT SYSTEM")
        self.root.geometry("1920x1080")
        self.root.config(bg="grey")
        #Decleartion of varables
        pId = StringVar()
        pName = StringVar()
        pPrice = StringVar()
        pQty = StringVar()
        pCompany = StringVar()
        pContact = StringVar()
        '''Declaring a Global Variable'''
        '''Calling the Data base Functions to perform operations'''
        #Function for Exit the appliction
        def Close():
            print("Product : Close method called")
            close = tkinter.messagebox.askyesno("WAREHOUSE INVENTORY SALES AND PURCHASE MANAGMENT SYSTEM","Are you Sure You Want to Exit")
            if close > 0:
                root.destroy()
                print("Product : close method finished\n")
                return
        #Function for clear\reset the Widgets
        def clear():
            print("Product : clear method called")
            self.txtpID.delete(0,END)
            self.txtpName.delete(0, END)
            self.txtpPrice.delete(0, END)
            self.txtpQty.delete(0, END)
            self.txtpCompany.delete(0, END)
            self.txtpContact.delete(0, END)
            print("Product : clear method finished\n")
        #Function to save the product details in data base table
        def insert():
            print ("Product : insert method called")
            if (len(pId.get()) != 0):
                p.insert(pId.get(),pName.get(),pQty.get(),pPrice.get(),pCompany.get(),pContact.get())
                productList.delete(0,END)
                productList.insert(END,pId.get(),pName.get(),pQty.get(),pPrice.get(),pCompany.get(),pContact.get())
                ShowInProductList() #caleed ShowInProductList after iserting the data in table
            else:
                tkinter.messagebox.askyesno("WAREHOUSE INVENTORY SALES AND PURCHASE MANAGMENT SYSTEM",
                                            "Enter Product ID")
            print("Product : insert method finised\n")
        #Function to show table data in Right body
        def ShowInProductList():
            print("Product : Showinproductlist method called")
            productList.delete(0, END)
            for row in p.show():
                productList.insert(END,row,str(""))
            print("Product")
        #function to add scroll bar
        def prodctRec(event):
            print("Product : productREc method is called")
            global pd
            searchPd = productList.curselection()[0]
            pd = productList.get(searchPd)
            self.txtpID.delete(0,END)
            self.txtpID.insert(END, pd[0])
            self.txtpName.delete(0, END)
            self.txtpName.insert(END, pd[1])
            self.txtpPrice.delete(0, END)
            self.txtpPrice.insert(END, pd[2])
            self.txtpQty.delete(0, END)
            self.txtpQty.insert(END, pd[3])
            self.txtpCompany.delete(0, END)
            self.txtpCompany.insert(END, pd[4])
            self.txtpContact.delete(0, END)
            self.txtpContact.insert(END, pd[5])
            print("Product : productRec method finished\n")
        #Function to delete data
        def delete():
            print("Product : delete method called")
            if (len(pId.get()) != 0):
                p.delete(pd[0])
                clear()
                ShowInProductList()
                print("Product : delete method finised\n")
        #search the record
        def search():
            print("Product : search method called")
            productList.delete(0,END)
            for row in p.search(pId.get(),pName.get(),pQty.get(),pPrice.get(),pCompany.get(),pContact.get()):
                productList.insert(END,row,str(""))
            print("Product : search methos finished\n")
        #FUnction to update
        def update():
            print("Product : update method called")
            if(len(pId.get())!= 0):
                print("pd[0]",pd[p])
                p.delete(pd[0])
            if (len(pId.get()) != 0):
                p.insert(pId.get(), pName.get(), pQty.get(), pPrice.get(), pCompany.get(), pContact.get())
                productList.delete(0,END)
            productList.insert(END,(pId.get(), pName.get(), pQty.get(), pPrice.get(), pCompany.get(), pContact.get()))
            print("Product :update method finised")
        '''create the frame'''
        MainFrame = Frame(self.root, bg="black")
        MainFrame.grid()
        HeadFrame = Frame(MainFrame, bd=1, padx=110, pady=10, bg='#003973', relief=RIDGE)
        HeadFrame.pack(side=TOP)
        self.ITitle = Label(HeadFrame, font=('ariel', 50, 'bold'), fg='white',
                            text='Warehouse Inventory Sales And Purchase', bg='#003973')
        self.ITitle.grid()
        OperationFrame = Frame(MainFrame, bd=3, width=1300, height=60, padx=450, pady=20, bg='white', relief=RIDGE)
        OperationFrame.pack(side=BOTTOM)
        BodyFrame = Frame(MainFrame, bd=2, width=1290, height=400, padx=65, pady=20, bg='#dcdde1', relief=RIDGE)
        BodyFrame.pack(side=BOTTOM)
        LeftBodyFrame = LabelFrame(BodyFrame, bd=4, width=600, height=380, padx=51, pady=50, bg='#eee', relief=RIDGE,
                                   font=('arial', 15, 'bold'), text='Product Item Details:')
        LeftBodyFrame.pack(side=LEFT)
        RightBodyFrame = LabelFrame(BodyFrame, bd=4, width=400, height=380, padx=20, pady=88, bg='#eee', relief=RIDGE,
                                    font=('arial', 15, 'bold'), text='Product Item Information:')
        RightBodyFrame.pack(side=RIGHT)
        #code for widgets on LeftBodyFrame
        self.lablepID = Label(LeftBodyFrame, font=('arial', 15, 'bold'), text='Product ID :', padx=2, pady=2,
                              bg='#eee', fg='black')
        self.lablepID.grid(row=0, column=0, sticky=W)
        self.txtpID = Entry(LeftBodyFrame, font=('arial', 20, 'bold'), textvariable=pId, width=35)
        self.txtpID.grid(row=0, column=1, sticky=W)
        self.lablepC1 = Label(LeftBodyFrame, padx=2, pady=2, bg='#eee')
        self.lablepC1.grid(row=1, column=0, sticky=W)
        self.lablepName = Label(LeftBodyFrame, font=('arial', 15, 'bold'), text='Product Name :', padx=2, pady=2,
                                bg='#eee', fg='black')
        self.lablepName.grid(row=2, column=0, sticky=W)
        self.txtpName = Entry(LeftBodyFrame, font=('arial', 20, 'bold'), textvariable=pName, width=35)
        self.txtpName.grid(row=2, column=1, sticky=W)
        self.lablepC2 = Label(LeftBodyFrame, padx=2, pady=2, bg='#eee')
        self.lablepC2.grid(row=3, column=0, sticky=W)
        self.lablepPrice = Label(LeftBodyFrame, font=('arial', 15, 'bold'), text='Product Price :', padx=2, pady=2,
                                 bg='#eee', fg='black')
        self.lablepPrice.grid(row=4, column=0, sticky=W)
        self.txtpPrice = Entry(LeftBodyFrame, font=('arial', 20, 'bold'), textvariable=pPrice, width=35)
        self.txtpPrice.grid(row=4, column=1, sticky=W)
        self.lablepC3 = Label(LeftBodyFrame, padx=2, pady=2, bg='#eee')
        self.lablepC3.grid(row=5, column=0, sticky=W)
        self.lablepQty = Label(LeftBodyFrame, font=('arial', 15, 'bold'), text='Product Quantity :', padx=2, pady=2,
                               bg='#eee', fg='black')
        self.lablepQty.grid(row=6, column=0, sticky=W)
        self.txtpQty = Entry(LeftBodyFrame, font=('arial', 20, 'bold'), textvariable=pQty, width=35)
        self.txtpQty.grid(row=6, column=1, sticky=W)
        self.lablepC4 = Label(LeftBodyFrame, padx=2, pady=2, bg='#eee')
        self.lablepC4.grid(row=7, column=0, sticky=W)
        self.lablepCompany = Label(LeftBodyFrame, font=('arial', 15, 'bold'), text='Manufacturing Company :', padx=2,
                                   pady=2, bg='#eee', fg='black')
        self.lablepCompany.grid(row=8, column=0, sticky=W)
        self.txtpCompany = Entry(LeftBodyFrame, font=('arial', 20, 'bold'), textvariable=pCompany, width=35)
        self.txtpCompany.grid(row=8, column=1, sticky=W)
        self.lablepC5 = Label(LeftBodyFrame, padx=2, pady=2, bg='#eee')
        self.lablepC5.grid(row=9, column=0, sticky=W)
        self.lablepContact = Label(LeftBodyFrame, font=('arial', 15, 'bold'), text='Company Contact :', padx=2, pady=2,
                                   bg='#eee', fg='black')
        self.lablepContact.grid(row=10, column=0, sticky=W)
        self.txtpContact = Entry(LeftBodyFrame, font=('arial', 20, 'bold'), textvariable=pContact, width=35)
        self.txtpContact.grid(row=10, column=1, sticky=W)
        self.lablepC6 = Label(LeftBodyFrame, padx=2, pady=2, bg='#eee')
        self.lablepC6.grid(row=11, column=0, sticky=W)
        '''scrollbar code'''
        scroll = Scrollbar(RightBodyFrame)
        scroll.grid(row=0, column=1, sticky='ns')
        productList = Listbox(RightBodyFrame, width=40, height=16, font=('arial', 12, 'bold'),
                              yscrollcommand=scroll.set)
        #called above created prodctRec
        productList.bind('<<ListboxSelect>>',prodctRec)
        productList.grid(row=0, column=0, padx=8)
        scroll.config(command=productList.yview)
        '''buttons'''
        #Code to create the Save button
        self.buttonSave = Button(LeftBodyFrame, text='Save', fg='white', font=('arial', 12, 'bold'), bg='#009432',
                                 height=1, width=8, bd=4,command = insert)
        self.buttonSave.grid(row=12, column=5)
        # Code to create the Showdata button
        self.buttonShowData = Button(OperationFrame, text='Show Data', fg='white', font=('arial', 15, 'bold'),
                                     bg='#f39c12', height=1, width=8,
                                     bd=4,command = ShowInProductList)
        self.buttonShowData.grid(row=0, column=1)
        # Code to create the Clear button
        self.buttonClear = Button(OperationFrame, text='Clear', fg='white', font=('arial', 15, 'bold'), bg='#487eb0',
                                  height=1, width=8, bd=4,command = clear)
        self.buttonClear.grid(row=0, column=2)
        # Code to create the Delete button
        self.buttonDelete = Button(OperationFrame, text='Delete', fg='white', font=('arial', 15, 'bold'), bg='#c0392b',
                                   height=1, width=8, bd=4,command = delete)
        self.buttonDelete.grid(row=0, column=5)
        # Code to create the Search button
        self.buttonSearch = Button(OperationFrame, text='Search', fg='white', font=('arial', 15, 'bold'), bg='#2ecc71',
                                   height=1, width=8, bd=4,command = search)
        self.buttonSearch.grid(row=0, column=7)
        # Code to create the Upgrade button
        self.buttonUpdate = Button(OperationFrame, text='Update', fg='white', font=('arial', 15, 'bold'), bg='#60a3bc',
                                   height=1, width=8, bd=4,command = update)
        self.buttonUpdate.grid(row=0, column=9)
        # Code to create the Close button
        self.buttonClose = Button(OperationFrame, text='Close', fg='white', font=('arial', 15, 'bold'), bg='#eb2f06',
                                  height=1, width=8, bd=4,command =Close)
        self.buttonClose.grid(row=0, column=11)
#Back End DataBase Operations Code
class Database:
    #Function to connect the program with the data base
    def conn(self):
        print("Data base : Connection Method Called")
        con = sqlite3.connect("inventory.db")
        cur = con.cursor()
        query = "Create table if not exists product(pid integer primery key,pname text,price text,qty text,company text,contact text)"
        cur.execute(query)
        con.commit()
        con.close()
        print("Data base : Connection Method finished\n")
    #Function to insert the data into the data base
    def insert(self, pid,name,price,qty,company,contact):
        print("Data base : Connection Method Called")
        con = sqlite3.connect("inventory.db")
        cur = con.cursor()
        query = "insert into product values(?,?,?,?,?,?)"
        cur.execute(query,(pid,name,qty,price,company,contact))
        con.commit()
        con.close()
    #Function to Show the data in the data base
    def show(self):
        print("Data base : Connection Method Called")
        con = sqlite3.connect("inventory.db")
        cur = con.cursor()
        query = "select * from product"
        cur.execute(query)
        rows = cur.fetchall()
        con.close()
        print("Data base : ShowData Method finished\n")
        return rows
    #Function to delete the data from the data base
    def delete(self,pid):
        print("Data base : Connection Method Called",pid)
        con = sqlite3.connect("inventory.db")
        cur = con.cursor()
        cur.execute("delete from product where pid=?",(pid,))
        con.commit()
        con.close()
        print(pid,"Data base : Delete Method finished\n")
    #Function to Search the data from the data base
    def search(self,pid="",name="",price="",qty="",company="",contact=""):
        print("Data base : Connection Method Called", pid)
        con = sqlite3.connect("inventory.db")
        cur = con.cursor()
        cur.execute("select * from product where pid=? or pname=? or price=? or qty=? or company=? or contact=?",(pid,name,price,qty,company,contact))
        row = cur.fetchall()
        con.close()
        print("Data base :Search method is finised\n")
        return row
    #Function to Update the data base
    def update(self,pid="",name="",price="",qty="",company="",contact=""):
        print("Data base : Connection Method Called", pid)
        con = sqlite3.connect("inventory.db")
        cur = con.cursor()
        cur.execute("update product set pid=? or pname=? or price=? or qty=? or company=? or or contact=? where pid =?",(pid,name,price,qty,company,contact,pid))
        con.commit()
        con.close()
        print(pid,"Data base : update method finised \n")
#Main function
if __name__ == '__main__':
    root = Tk()
    application = product(root)
    root.mainloop()