Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
6.6 kB
2
Indexable
Never
import tkinter as tk
from tkinter import messagebox
import json
from jsonFile import handel_file_json
from cartpagefinallll import CartPage
from itemPage import itemsPage

class Categories:
    def __init__(self, root, category_name, go_back_callback, user):
        self.page_stack = []  
        self.root = root
        self.go_back_callback = go_back_callback
        self.root.title("Category Selection")
        self.root.geometry("500x500")
        self.items = self.load_items()
        self.sorted_items = {category: list(items) for category, items in self.items.items()}
        self.cart = {}
        self.user = user
        self.open_category_page(category_name)

    def go_back(self):
        if len(self.page_stack) > 1:
            self.page_stack.pop()
            previous_page = self.page_stack[-1]
            if previous_page == "Main Categories":
                self.load_main_page()
            else:
                self.open_category_page(previous_page)
        else:
            self.go_back_callback()

    def load_items(self):
        with open('items.json', 'r') as file:
            return json.load(file)

    def save_items(self):
        with open('items.json', 'w') as file:
            json.dump(self.items, file, indent=4)

    def open_category_page(self, category_name):
        for widget in self.root.winfo_children():
            widget.destroy()

        if category_name not in self.page_stack:
            self.page_stack.append(category_name)

        tk.Label(self.root, text=f"Welcome to the {category_name} Page", font=("arial", 20)).pack(pady=20)

        self.search_var = tk.StringVar()
        tk.Entry(self.root, textvariable=self.search_var, width=30).pack(pady=10)
        tk.Button(self.root, text="Search", command=lambda: self.search_items(category_name)).pack(pady=10)

        tk.Button(self.root, text="Sort Ascending", command=lambda: self.sort_items(category_name, ascending=True)).pack(pady=10)
        tk.Button(self.root, text="Sort Descending", command=lambda: self.sort_items(category_name, ascending=False)).pack(pady=10)

        tk.Button(self.root, text="Proceed to Checkout", command=self.open_cart_pagee).pack(pady=10)
        tk.Button(self.root, text="Back to Home", command=self.return_to_home).pack(pady=10)

        self.display_items(category_name)

    def search_items(self, category_name):
        search_term = self.search_var.get().strip().lower()
        items = self.sorted_items[category_name]
        filtered_items = [item for item in items if search_term in item['name'].lower()]
        self.display_filtered_items(filtered_items)
        
        
    def binary_search(self, items, target_name):
        low, high = 0, len(items) - 1
        while low <= high:
            mid = (low + high) // 2
            mid_name = items[mid]['name'].lower()
            if mid_name == target_name:
                return [items[mid]]
            elif mid_name < target_name:
                low = mid + 1
            else:
                high = mid - 1
        return []


    def display_filtered_items(self, items):
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.Frame):
                widget.destroy()
        self.display_items_content(items)

    def quick_sort(self, items, low, high, ascending=True):
        if low < high:
            pi = self.partition(items, low, high, ascending)
            self.quick_sort(items, low, pi - 1, ascending)
            self.quick_sort(items, pi + 1, high, ascending)

    def partition(self, items, low, high, ascending=True):
        pivot = items[high]['price']
        i = low - 1
        for j in range(low, high):
            if (items[j]['price'] <= pivot) if ascending else (items[j]['price'] >= pivot):
                i += 1
                items[i], items[j] = items[j], items[i]
        items[i + 1], items[high] = items[high], items[i + 1]
        return i + 1

    def display_items(self, category_name):
        items = self.sorted_items[category_name]
        for widget in self.root.winfo_children():
            if isinstance(widget, tk.Frame):
                widget.destroy()
        self.display_items_content(items)

    def display_items_content(self, items):
        for item in items:
            item_frame = tk.Frame(self.root)
            item_frame.pack(pady=5)
            item_label = tk.Label(item_frame, text=f"Name: {item['name']}, Price: {item['price']}")
            item_label.pack(side="left", padx=5)
            qty_var = tk.IntVar(value=0)
            qty_spinbox = tk.Spinbox(item_frame, from_=0, to=100, textvariable=qty_var)
            qty_spinbox.pack(side="left", padx=5)
            add_button = tk.Button(item_frame, text="Add to Cart", command=lambda i=item, q=qty_var: self.add_to_cart(i, q))
            add_button.pack(side="left", padx=5)

    def add_to_cart(self, item, qty_var):
        quantity = qty_var.get()
        if quantity > 0:
            cart_data = self.cart[item['name']] = {
                'user_id': self.user["id"],
                'price': item['price'],
                'quantity': quantity,
                'product_name': item['name']
            }
            js = handel_file_json()
            js.adde("Cart", cart_data)

            messagebox.showinfo("Cart", f"Added {quantity} of {item['name']} to cart!")
        else:
            messagebox.showwarning("Quantity Error", "Please select a valid quantity.")

    def open_cart_page(self):
        for widget in self.root.winfo_children():
            widget.destroy()
        tk.Label(self.root, text="This is the Cart Page", font=("arial", 20)).pack(pady=20)
        if self.cart:
            for item_name, details in self.cart.items():
                tk.Label(self.root, text=f"{item_name}: {details['quantity']} @ ${details['price']} each").pack()
            total_price = sum(details['price'] * details['quantity'] for details in self.cart.values())
            tk.Label(self.root, text=f"Total Price: ${total_price}").pack(pady=10)
        else:
            tk.Label(self.root, text="You have not selected any products.").pack(pady=10)

        tk.Button(self.root, text="Back to Home", command=self.return_to_home).pack(pady=10)

    def return_to_home(self):

        for widget in self.root.winfo_children():
            widget.destroy()
        itemsPage(self.root, self.go_back_callback, self.user)

    def open_cart_pagee(self):
        CartPage(self.user)
Leave a Comment