from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import Tk, Label
from PIL import ImageTk, Image
import os



def crc():
    try:
        filename = entry.get()
        divisor = entry2.get()
        seqnumber = 0
        frame_count = 0  # Counter for converted frames
        with open(filename, "rb") as file:
            while True:
                seqnumber += 1
                sqn = bin(seqnumber)[2:].zfill(16)
                data_txt = file.read(1024)
                if not data_txt:
                    break
                div = "".join(map("{:08b}".format, data_txt))
                divident = div
                while len(divident) >= len(divisor):
                    rez = ''
                    bb = divident[:len(divisor)]
                    divident = divident[len(divisor):]
                    f = 0
                    for i in range(0, len(divisor)):
                        if bb[i] != divisor[i]:
                            f = 1
                            rez += '1'
                        if bb[i] == divisor[i] and f == 1:
                            rez += '0'
                    divident = rez + divident
                crc = divident.zfill(16)
                address = bin(id(file))[2:].zfill(16)
                frame = sqn + address + div + crc
                with open("frame.txt", "a") as file2:
                    file2.write(frame)
                frame_count += 1  # Increment the frame counter

        label3.config(text="Файл сконвертирован и записан!",)
        label5.config(text=f"Количество отправленных пакетов: {frame_count}")
    except FileNotFoundError:
        label3.config(text="Ошибка: Файл не найден!")
    except IOError:
        label3.config(text="Ошибка: Не удалось прочитать файл!")
    except Exception as e:
        label3.config(text=f"Ошибка: {str(e)}")

def choose_file():
    try:
        filename = filedialog.askopenfilename()
        entry.delete(0, END)
        entry.insert(0, filename)
        file_size = os.path.getsize(filename)
        label4.config(text=f"Вес файла: {file_size} байт")
    except FileNotFoundError:
        label4.config(text="Ошибка: Файл не найден!")
    except Exception as e:
        label4.config(text=f"Ошибка: {str(e)}")

root = Tk()
root.title("CRC Calculator")
root.geometry("400x265")
root.resizable(False, False)

style = ttk.Style()
style.configure("TLabel", font=("Arial", 12))
style.configure("TButton", font=("Arial", 12), background="lime green")


background_image = ImageTk.PhotoImage(Image.open("raketa.jpg"))
background_label = Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)


label1 = ttk.Label(text="Напишите название файла:", font=("Arial", 12, "bold"))
label1.pack()

entry = ttk.Entry(font=("Arial", 12))
entry.pack(ipadx=10, ipady=6, padx=120, pady=5)

btn_choose = ttk.Button(text="Выбрать файл", command=choose_file)
btn_choose.pack()

label4 = ttk.Label(text="")
label4.pack()

label2 = ttk.Label(text="Введите полином:", font=("Arial", 12, "bold"))
label2.pack()

entry2 = ttk.Entry(font=("Arial", 12))
entry2.pack(ipadx=10, ipady=6, padx=120, pady=5)

btn1 = ttk.Button(text="Вычислить CRC и отправить", command=crc)
btn1.pack()

label3 = ttk.Label(text="")
label3.pack()

label5 = ttk.Label(text="")
label5.pack()


root.mainloop()