# faq_screen.py
# Versão: 2.4 (Ajustes de Estilo na Busca e Perguntas)
# Data: 25/06/2025
# Descrição: Módulo de FAQ com caixa de busca estilizada e fontes ajustadas.

import tkinter as tk
from tkinter import ttk

# Cores e Fontes
COLOR_BG = "#F5F5F5"
COLOR_SECTION_BG = "#EAEAEA"
COLOR_TEXT = "#333333"
COLOR_QUESTION_BG = "#E0E0E0"
COLOR_QUESTION_FG = "#000000"
COLOR_SEARCH_BG = "#FFFFE0" # Amarelo claro para a caixa de busca

# --- FONTE MODIFICADA AQUI (sem negrito) ---
FONT_QUESTION = ("Segoe UI", 10)
# ------------------------------------------
FONT_ANSWER = ("Segoe UI", 10)


class AccordionItem(tk.Frame):
    """ Um item individual do FAQ (uma pergunta e uma resposta). """
    def __init__(self, parent, question, answer, **kwargs):
        super().__init__(parent, **kwargs)
        self.configure(bg=COLOR_BG)
        self.is_expanded = False

        self.question_text = question
        self.answer_text = answer

        question_frame = tk.Frame(self, bg=COLOR_QUESTION_BG)
        question_frame.pack(fill="x", pady=(0, 1))

        self.question_button = tk.Button(
            question_frame,
            text=f">  {self.question_text}",
            anchor="w",
            justify="left",
            font=FONT_QUESTION,
            bg=COLOR_QUESTION_BG,
            fg=COLOR_QUESTION_FG,
            activebackground="#C5C5C5",
            activeforeground=COLOR_QUESTION_FG,
            relief=tk.FLAT,
            borderwidth=0,
            command=self.toggle
        )
        self.question_button.pack(fill="x", padx=10, pady=5)

        self.answer_frame = tk.Frame(self, bg=COLOR_SECTION_BG)
        self.answer_label = tk.Label(
            self.answer_frame,
            text=self.answer_text,
            font=FONT_ANSWER,
            bg=COLOR_SECTION_BG,
            fg=COLOR_TEXT,
            wraplength=850,
            justify="left",
            padx=15,
            pady=10
        )
        self.answer_label.pack(fill="x")

    def toggle(self):
        """ Alterna a visibilidade da resposta. """
        if self.is_expanded:
            self.answer_frame.pack_forget()
            self.question_button.config(text=f">  {self.question_text}")
            self.is_expanded = False
        else:
            self.answer_frame.pack(fill="x", pady=(0, 5), padx=5)
            self.question_button.config(text=f"v  {self.question_text}")
            self.is_expanded = True


class FaqScreen(tk.Frame):
    """ A classe principal que constrói a tela de FAQ com busca. """
    def __init__(self, parent):
        super().__init__(parent, bg=COLOR_BG)
        self.pack(fill="both", expand=True)

        self.faq_data = [
             ("How to position the equipment and tag to be evaluated ?", "The original antenna has a traditional transmission patern of a dipole . Position the tag facing the original antenna."),
             ("What is the requirement for the computer operational system ?", "Windows 7 or greater"),
             ("What is the minimal required hardware configuration ?", "Processor: Intel i3 | Memory: 2Gb | Disk Space: 250gb"),
             ("Is that possible to use a different antenna ?", "You can use a different antenna but the results will be different depending on the gain of the antenna."),
             ("Are the measurements absoture or relative values ?", "The measurement are relative values. You can measure a tag performance relative to another tags"),
             ("What are the principal conditions to compare tags performance ?", "Tags performance comparision must be done under the same distance and position of the equipment and the tags thenselves in order to have a consistent comparisions."),
             ("What to do if the module power reach the limits of 5dBm or 25dBm ?", "If the module reach the minimum value of 5 dB we recommend to increase the distance of the measurement. If the module reach 25 dB we recomend to reduce the distance. For both situations, even if they happen at the same distance of measurement we recomend to focus in the interested frequency range and adjust the distance appropriated."),
             ("What to do if there is test progress but there is no ploted results ?", "Check if the tag is already registered. Check if the tag is highlited in the registered tag list. Check if you have the right distance, reduce the distance if necessary. Check the alignment of the original antenna and the tag."),
             ("What to do if there are some fails in the ploted line of the results ?", "Fails are normally caused by module reaching the limits of 5dBm or 25 dBm. Adjusting the properly distance for the measurement will help to solve this problem unless if it is a intrinsic tag preformance behaviour."),
             ("What is the module power ?", "The module power is the Radio Frequency power generated by the operational module."),
             ("What is irradiated power ?", "The irradiated power represent the power of the module that is carryed out to the antenna and irradiated from it."),
             ("What is the backscattered power ?", "The backsccatered power It is the received reflected signal from the tag."),
             ("What is threshold point ?", "The threshold point is the minimal transmitted power to complete a interrogation communication to the tag."),
             ("Why is the threshold important to measure the performance of a tag ?", "The threshold is important because it determine the tag sensitivity. "),
             ("What do I have to do when I have to registed a tag and there are others tags arround ?", "We recomend to have the tag to be registered very close to the equipment antenna and obswerve the better RSSI signal strengh received that will be from the closest tag. The measurement of a tag having others tags arround may affect the measurements but some times if it is representing what is happened in practice you will have to keep the tags as there are."),
             ("What do I have to do if I cannot register a tag ?", "Plase the tag close to the antenna. Increase the power. Check id the tag is OK. "),
             ("Is that important the measument distance ?", "Yes, principally if you will compare several tags performance. It is necessaty to adjust the distance to have the measurements within the module power limits under the frequency range of interest. The distance must be the same when comparing tags performance."),
             ("When do I have to specify a determined frequency band ?", "Determining the frequency band will reduce the test time and will help you to focus in the range frequency of interest."),
             ("What mean the shaded area in the graphics ?", "The shaded areas in the grafics represent ETSI and FCC frequency bands. It helps you to identify if a tag is well tunned for the frequency and also helps you to do performance comparisions in the band of interest."),
             ("Is that necessary to apply a Tag in a product in order to evaluate its performance ?", "Yes. Most of the tags are made to be operated when used in cartoom box, plastic, wood, etc. We recommend to aply the tag in the product to evaluate its operation and find a right place in it to get better performance."),
             ("How do I know that a tag is tuned ?", "You will observe that it will require less power in the frequency of interest."),
             ("What to do if the equipment stop to work with a message of high temperature ?", "It indicates that for equipment protection a rest time is necessary in order to cool the device."),
             ("What is the temperature Limit ?", "It is the maximum internal temperature to avoid a internal demage of the module"),
             ("What to do if the equipment stop to work with a message to check the antenna ?", "Check the antenna position and any metalic material arround it."),
             ("What is the limit for Antenna Fail ?", "The limit for the antenna fall is a combination of the power modute intensity and the VSWR of the antenna."),
             ("What do I have to do if I just finish testing a tag and when testing another tag to compare the results the module reach its limits of 5 or 25 dBm ?", "If the module limits are under the frequency range of interest you have to adjust the distance and run again the test in all the tags used in the experiment."),
             ("Is that possible that a noise can affect the measurement ?", "Yes, it is possible. Check the Noise --> \"Noise Check\""),
             ("What do I have to do in order to redure the ambient noise ?", "Check other equipoments arround under operation like cell phones and RFID readers. It is not very frequent but others elctrical equipment can also affect the measurements."),
             ("How is the right way to transport the equipment and antenna ?", "Disconect the original antenna and USB cacle from the equipment. Transport them in a protected box. The original shipment box is a good example for a good transportation if you saved it."),
             ("How to get information regarding the software ?", "Access the License Page"),
             ("What do I have to do to know the license validation ?", "Access the License Page and click on Reload System Information"),
             ("How to obtain the operation license ?", "Access the License Page, click on button Auto License write the Token that was given by e-mail and then click on Register"),
             ("How can I know if my license will have an experition date ?", "It will be writen on License Page"),
             ("What to do if the equipment tells that there is no registration and license ?", ""),
             ("What is the \"Reload Information\"used for ?", "This is used to recall the license information"),
             ("What is the Register License used for ?", "It is necessary to get the necessary software information to access rhe hardware"),
             ("What is the Import Licence used for ?", "If you cannot get it through the internet you can recover it from a previous saved license"),
             ("What is the Export Licence used for ?", "It is used to save your license in a separated location"),
             ("What is the Software version?", "It is the control number of software for features and operation"),
             ("What is the Hardware Version ?", "It is the control number of the hardware for features and operation"),
             ("What is the Firmware Version ?", "It is the control number for the internal software resident in the hardware"),
             ("What is the frequency range ?", "It is the selected range you can set for the equipment operation"),
             ("What is the License type ?", "It is the type pf license you have for the released options for the equipment operation "),
             ("What is the Power Range ?", "It is the range from minimum power to the maximum power of the equipment"),
             ("What is the Power Step ?", "It is the increments of power during the execution of the power range"),
             ("Whayt is the License Issue Date ?", "It is the date of the purchase of the license"),
             ("What is the Serial ?", "It is the serial number of the hardware"),
             ("What is the Expiration Date ?", "It is the date of expiration of a license"),
             ("What is in the www.getfasttag.com ?", "It is the site containing all information pertaining to the Fasttag line of products"),
             ("What is the star buton in the Noise check ?", "It is the start for the Noise check measurement."),
             ("What is the Stop buton in the Noise check ?", "It is the stop for the Noise check measurement."),
             ("What is the clear graph in the Noise check ?", "It is used to clear the Noise check graphics in the screen"),
             ("What is the warranty of the equipment ?", "It is 1 year from the acquisition date."),
             ("What is the warning messages for Antenna Check ?", "It inditates thay the antenna is not well coupled with the equipment or that there is a close object that is interfering in the antenna operation"),
             ("What is the warning messages for Teperature ?", "It indicates that the equipment has a high internal temperature and have to rest in order to cool it down"),
             ("What is used for the power butom of the antenna check ?", "The power buttom is used to verify if the antenna, even with a matching problem can be operated under a reduction of the power."),
             ("What is the red line in the graph ?", "It indicates the maximum allower value where the equipment stop its operation in order to be protected "),
             ("What means the message FAIL Antenna Failure and what I have to do to fix it ?", "It indicates a problem in the antenna. Check its position and if it is well connected to the equipment. If you are using a different antenna check if there is any problem in the cable and connectors. Check if the antenna you are using has a 50 Ohm impedance. Check if there is any object close to the antenna causing a problem in its operation."),
             ("What is the used communicaton protocol ?", "Is the protocol of operation during the interrogation process to the tag under test"),
             ("Is the antenna polarization important ?", "Yes, it must me aligned with the tag in order to get a better result. Measurements in a blind area of the antenna or in the tag may result in a poor performance of the tag and even a fail in the measurements."),
             ("How to do the antenna and tag alignment ?", "The original antenna has a traditional dipole irradioation path. Check the tag under measurement for its irradiation path in order to align it with the antenna"),
             ("Is that necessary to run measuments in a non aligned positions ?", "Some times it is necessary if you have a special condition for the antenna and tag that cannot be changed by imposition of the setup. In thos situation the tag performance may be poor and even have a non operation for the blind areas of the arrangement antenna / taq"),
             ("What is this equipment used for ?", "It is used to identify the tag operation under a certain frequency range. It is also used to compare tgas performance and performance under different materials"),
             ("Who are the most user of this equipment ?", "This equipment was designed to professional users like system integrators, educational, etc"),
             ("Can I operate the equipment in na outdoor environment ?", "Yes but you have to follow the restrictions for dust and water splesh"),
             ("How do I have storage the equipment and what are the environment conditions ?", "Storage it in a fresh air condition with no presence of dust of water splesh"),
             ("How to register a new project ?", "In order to register a new project: click in \"Register a New Project\"; Write in the \"Project name Field\" the name of you project;click in \"Save\" buttom"),
             ("How to import a existing project ?", "To import an existing project click in the \"Import Project\" buttom; go to the folder the project is located and localize it (.gftb file type); click in open; "),
             ("How to export a project ?", "To expor an existing project click in \"Export\"buttom and the file will be saved in your specified folder."),
             ("What is a tag file type ?", "A tag file is caracterized by the file type \".json\""),
             ("How to register a new tag ?", "To register a new tag place a tag close to the antenna of the equipment. Go to Select an action --> Register New Tags --> Select Power --> Start Search"),
             ("What is used for the power adjustment when registering a tag ?", "You can adjust the power adjustment to the minimum value to reach the tag you want to register in order to avoid to reach other tags in the neiborhood."),
             ("What are the EPC and RSSI when registering a Tag ?", "When registering a new tag the EPC is the tag identification and RSSI is the strengh of its backscattering signal"),
             ("What is used for the RSSI intensity order buttom for the found tags to be registered ?", "During the \"register a new tag\" process it may result in more than 1 tag lested even when using the minimal power. If that happens you can choose the most string RSSI signal to be considered from the tag that is more closed to the antenna. "),
             ("What is the frequency step used for ?", "The frequency steps are used to get the necessary frequency detail in the measurements."),
             ("What is used for the field \"description\"?", "The field description of a measurement set up helps you to identify the measurement."),
             ("What to do if the start buttom is nor working ?", "If the start buttom is not working you may check if you have already registered any tag and if it is highlighted."),
        ]
        
        title_frame = tk.Frame(self, bg=COLOR_BG)
        title_frame.pack(fill="x", pady=(10, 2))
        tk.Label(title_frame, text="FAQ / Help", font=("Segoe UI", 16, "bold"), bg=COLOR_BG, fg=COLOR_TEXT).pack()
        
        # --- Search Box com Estilo e Largura Ajustados ---
        search_frame = tk.Frame(self, bg=COLOR_BG)
        # pack() sem fill/expand centraliza o frame
        search_frame.pack(pady=5)

        tk.Label(search_frame, text="Buscar:", font=("Segoe UI", 10), bg=COLOR_BG).pack(side="left", padx=(5,5))
        
        self.search_var = tk.StringVar()
        self.search_var.trace_add("write", self._filter_faq)
        search_entry = tk.Entry(
            search_frame, 
            textvariable=self.search_var, 
            font=("Segoe UI", 10), 
            width=60, # Largura reduzida
            bg=COLOR_SEARCH_BG, # Cor de fundo para destaque
            relief=tk.SOLID,
            borderwidth=1
        )
        search_entry.pack(side="left")
        # --- Fim da Modificação ---

        canvas_container = tk.Frame(self)
        canvas_container.pack(fill="both", expand=True, padx=20, pady=10)
        
        self.canvas = tk.Canvas(canvas_container, bg=COLOR_BG, highlightthickness=0)
        scrollbar = ttk.Scrollbar(canvas_container, orient="vertical", command=self.canvas.yview)
        self.scrollable_frame = tk.Frame(self.canvas, bg=COLOR_BG)

        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        )

        self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.canvas.configure(yscrollcommand=scrollbar.set)

        self.canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        self._populate_faq()

    def _populate_faq(self, filter_term=""):
        """Limpa e recria a lista de itens do FAQ com base em um filtro."""
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
            
        term = filter_term.lower()
        
        items_found = False
        for q, a in self.faq_data:
            if term in q.lower() or term in a.lower():
                item = AccordionItem(self.scrollable_frame, question=q, answer=a)
                item.pack(fill="x", expand=True, padx=10, pady=2)
                items_found = True
        
        if not items_found:
             tk.Label(self.scrollable_frame, text="Nenhum resultado encontrado.", font=FONT_ANSWER, bg=COLOR_BG).pack()

        self._bind_mousewheel_recursively(self.scrollable_frame)

    def _filter_faq(self, *args):
        """Função chamada sempre que o texto de busca muda."""
        search_term = self.search_var.get()
        self._populate_faq(filter_term=search_term)

    def _on_mousewheel(self, event):
        self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

    def _bind_mousewheel_recursively(self, widget):
        widget.bind("<MouseWheel>", self._on_mousewheel)
        for child in widget.winfo_children():
            self._bind_mousewheel_recursively(child)

# --- Bloco de Teste Isolado ---
if __name__ == '__main__':
    root = tk.Tk()
    root.title("Teste - Tela de FAQ")
    root.geometry("950x750")
    
    faq_app = FaqScreen(root)
    
    root.mainloop()