import ipywidgets as widgets
import tkinter as tk
from tkinter import filedialog
import tkinter.messagebox
import numpy as np


def add_widgets_to_list(source_dictionary,target_list):
    for widget in source_dictionary.values():
        target_list.append(widget)


def change_state(widgets_list):
    for widget in widgets_list:
        widget.disabled = not widget.disabled


def ask_for_calibration():
    root = tk.Tk()
    root.withdraw()
    root.attributes("-topmost",True)
    root.update()
    answer=tk.messagebox.askyesno(message='Do you want to calibarate?')

    root.destroy()
    return answer

def save_file(default_filename):
    root = tk.Tk()
    root.withdraw()
    root.lift() #show window above all other applications

    root.attributes("-topmost", True)#window stays above all other applications

    file = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Txt files","*.txt")],title = "save results",initialfile =default_filename)

    while file.endswith(".txt") == False:
        file = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Txt files","*.txt")],title = "save results",initialfile =default_filename)

    root.destroy()
    return file

def information_box(information):
    #open dialog and hide the main window
    root = tk.Tk()
    root.withdraw()
    root.lift() #show window above all other applications

    root.attributes("-topmost", True)#window stays above all other applications

    #display meaagebox
    tkinter.messagebox.showinfo(message=information)
    root.destroy()

def check_values(voltage:dict,freq:dict):

    if abs(voltage["step"].value) > abs(voltage["stop"].value-voltage["start"].value) or abs(voltage["step"].value)<0.01:
        return False
    
    #Invert Polarity if nesaccary
    if voltage["stop"].value > voltage["start"].value and voltage["step"].value < 0:
        voltage["step"].value = -voltage["step"].value
    elif voltage["stop"].value < voltage["start"].value and voltage["step"].value > 0:
        voltage["step"].value = -voltage["step"].value
    else:
        pass

    # Now lets check for correct plots

    # calculate the number of points for voltage
    voltage_points = abs(voltage["stop"].value-voltage["start"].value)/abs(voltage["step"].value) + 1

    if voltage["v_point"].value > voltage_points:
        return False
    
    # prove that we check a valld frequency point
    if voltage["f_point"].value > freq['nop'].value:
        return False
    return True

# create array for hysteris and remove the last element
def reversed_array(arr):
    arr = list(arr)
    arr.pop()
    arr.reverse()
    return np.array(arr)