import copy
import math

import pygame

import colors
from objects.Characters import get_all_characters
from objects.miscsprites import PawButton
from utils.lights import ColorLib
from utils.sounds import SoundLib

all_chars = get_all_characters()
from sprites.CharacterSelectCharacter import CharacterSelectCharacter
import vars

class CharacterWheelNew:
    color = (150, 150, 150)
    inc = (0, 0, 0)
    final_color = (150, 150, 150)
    counter = 0

    def __init__(self, x, y, blend_frames, angle_offset, align_x=1, min_selected_angle=0, max_selected_angle=0, reverse_stats=False):
        self.spawn_counter = 0
        self.confirmed = False
        self.x = x
        self.y = y
        self.characters = []
        self.angle_counter = 0
        self.final_angle = 0
        self.angle = 0
        self.moving = 0
        self.spawning = False
        self.spawned = False
        self.despawning = False
        self.despawned = False
        self.despawn_counter = 0
        self.reverse_stats = reverse_stats
        self.blend_frames = blend_frames
        self.align_x = align_x
        self.flash_timer = 0
        self.angle_offset = angle_offset
        self.selected_character_index = 0
        self.radius = 0
        self.color = (0, 0, 0)
        self.all_colors = list()
        self.min_selected_angle = min_selected_angle
        self.max_selected_angle = max_selected_angle
        self.load_characters()

    def load_characters(self):
        char_indices = range(len(all_chars))
        # if self.factor < 0:
        #     char_indices = char_indices.__reversed__()

        angle_divis = int(360 / len(all_chars))
        angle_offset = int((self.min_selected_angle + self.max_selected_angle)/2)
        for i in char_indices:
            self.characters.append(
                CharacterSelectCharacter(all_chars[i](), int(angle_divis * i) + angle_offset, self.x, self.y, self.min_selected_angle, self.max_selected_angle))

        # temp_stupid_array = self.characters
        # # temp_stupid_array.reverse()
        # temp_stupid_array[-1].angle += (360 if temp_stupid_array[-1].angle <= 0 else 0)
        # all_colors = dict()
        # current_angle = temp_stupid_array[0].angle
        #
        # for i in range(0, len(temp_stupid_array)):
        #     start_color = temp_stupid_array[i].character.color
        #     end_color = temp_stupid_array[(i + 1)%len(temp_stupid_array)].character.color
        #     r_diff = end_color[0] - start_color[0]
        #     g_diff = end_color[1] - start_color[1]
        #     b_diff = end_color[2] - start_color[2]
        #
        #     start_angle = temp_stupid_array[i].angle
        #     end_angle = temp_stupid_array[(i + 1)%len(temp_stupid_array)].angle
        #     if start_angle > end_angle:
        #         end_angle += 360
        #     increments = end_angle-start_angle
        #
        #     for j in range(increments):
        #         new_r = (start_color[0] + ((j / increments) * r_diff))
        #         new_g = (start_color[1] + ((j / increments) * g_diff))
        #         new_b = (start_color[2] + ((j / increments) * b_diff))
        #
        #         new_color = (int(new_r), int(new_g), int(new_b))
        #
        #         # TODO:  Make this color thing work
        #         all_colors[current_angle] = new_color
        #         current_angle = (current_angle+1)%360
        #         # self.all_colors.append((255, 255, 255))
        #
        # self.all_colors = all_colors
        # TODO:  NONE OF THIS WORKS
        self.update_chars(0)  # Todo:  this is kind of hacky

    def confirm_character(self):
        if self.get_selected_character() is not None:
            SoundLib.playsound(self.get_selected_character().character.selectsound)

            if not self.confirmed:
                self.get_selected_character().flash_factor = 2
                self.flash_timer = 30
                self.confirmed = True

    def update_chars(self, angle_inc):
        if self.confirmed:
            angle_inc = 0
            return
        for char in self.characters:
            if (self.despawning or self.despawned) and char.selected:
                continue
            char.radius = self.radius + 30
            char.update(angle_inc)

    def get_selected_character(self):
        if not self.spawned and not self.spawning:
            return None
        if self.spawning:
            return None
        try:
            return [x for x in self.characters if x.selected][0]
        except:
            return None

    def update(self, angle):
        if not self.spawning and not self.spawned:
            return

        if self.spawning:
            self.spawn_counter += 1
            self.radius += 300 / self.blend_frames
            if self.spawn_counter > self.blend_frames:
                self.spawning = False
                self.spawned = True
        if self.despawning:
            self.despawn_counter += 1
            self.radius -= 300 / self.blend_frames
            if self.despawn_counter > self.blend_frames:
                self.despawning = False
                self.despawned = True

        self.flash_timer = max(self.flash_timer-1, 0)
        if self.flash_timer == 1:
            self.get_selected_character().flash_factor = 1000
        self.angle = (self.angle - angle) % 360
        self.update_chars(self.angle)
        selected_char = self.get_selected_character()
        if selected_char is not None:
            # if selected_char.angle < int((self.min_selected_angle + self.max_selected_angle) / 2):
            #     ratio = (self.angle - self.min_selected_angle) / ((self.max_selected_angle - self.min_selected_angle) / 2)
            # elif self.angle >= int((self.min_selected_angle + self.max_selected_angle) / 2):
            #     ratio = (self.max_selected_angle - self.angle) / ((self.max_selected_angle - self.min_selected_angle) / 2)
            #
            # self.scale = min(0.4 + ratio, 0.8)
            # TODO:  I DUNNO, FADE THE COLOR OR SOMETHING
            self.color = self.get_selected_character().character.color
        else:
            self.color = colors.white

    def spawn_or_confirm(self):
        if self.spawned and not self.despawned:
            if not self.moving:
                self.confirm_character()

                if self.confirmed:
                    if self.reverse_stats:  # False = player 1
                        ColorLib.set_colors(None, self.get_selected_character().character.colorcode)
                    elif not self.reverse_stats:
                        ColorLib.set_colors(self.get_selected_character().character.colorcode, None)

                    self.despawning = True
        elif not self.confirmed:
            self.spawning = True

    def draw_stats(self, screen):
        char = self.get_selected_character()
        if char is not None:
            if not self.moving:
                name = char.character.name
                stats = char.character.attributes
                font = pygame.font.SysFont('Impact', 25)

                max_label_width = 0
                for stat in stats:
                    label = font.render(stat, 1, colors.white)
                    max_label_width = max(max_label_width, label.get_width())

                label = font.render(name, 1, char.character.color)
                if self.reverse_stats:
                    screen.blit(label, (char.x - max_label_width - 10, char.y))
                else:
                    screen.blit(label, (char.x + char.width + 10, char.y))
                stat_y = char.y + 20
                for stat in stats:
                    label = font.render(stat, 1, colors.white)
                    if self.reverse_stats:
                        screen.blit(label, (char.x - max_label_width - 10, stat_y))
                    else:
                        screen.blit(label, (char.x + char.width + 10, stat_y))
                    stat_y += 20

                label = font.render('PRESS                     TO CONFIRM', 1, (200, 200, 200))
                screen.blit(label, (self.align_x - label.get_width()/2, vars.SCREEN_HEIGHT - 100))
                button = PawButton((self.align_x - label.get_width() / 2 + 70, vars.SCREEN_HEIGHT - 120))
                button.draw(screen, 0, 0)
                stat_y += 20

    def draw_circles(self, screen):
        pygame.draw.circle(screen, self.color, (self.x, self.y), int(self.radius + 90), 9)
        pygame.draw.circle(screen, self.color, (self.x, self.y), int(self.radius + 20), 4)
        pygame.draw.circle(screen, self.color, (self.x, self.y), int(self.radius + 5), 1)
        pygame.draw.circle(screen, self.color, (self.x, self.y), int(self.radius + 1), 1)

    def draw(self, screen):

        if not self.spawned and not self.spawning and not self.confirmed:
            font = pygame.font.SysFont('IMPACT', 30)
            label = font.render('   PRESS                TO JOIN', 1, (200, 200, 200))
            button = PawButton((self.align_x - label.get_width()/2+100, 180))
            screen.blit(label, (self.align_x - label.get_width()/2, 200))
            button.draw(screen, 0, 0)

        self.draw_circles(screen)

        if self.radius > 0 and not self.confirmed:
            self.draw_stats(screen)

        if self.confirmed:
            # TODO:  ugly
            if self.get_selected_character() is not None:
                font = pygame.font.SysFont('IMPACT', 40)
                label = font.render(self.get_selected_character().character.name, 1, self.get_selected_character().character.color)
                screen.blit(label, (self.align_x - label.get_width()/2, 650))

        if self.spawning or self.spawned:
            if not self.confirmed:
                for char in sorted(self.characters, key=lambda c: c.scale):
                    char.draw(screen)

            else:
                self.get_selected_character().draw(screen)


from pyfirmata import Arduino, util
import time
import pyfirmata

# Morse code dictionary
morse_code_dict = {
    'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.',
    'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.',
    'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-',
    'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..',
    '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....',
    '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----',
    '.': '.-.-.-', ',': '--..--',' ':'.......'
}

# Connect to the Arduino board
board = Arduino('COM26')  # Update this with the correct serial port

# Define the LED pin and photoresistor pin
led_pin = 8
photoresistor_pin = 0  # Analog pin 0

board.digital[led_pin].mode = pyfirmata.OUTPUT
analog_input = board.get_pin('a:0:i')
it = util.Iterator(board)
it.start()

def read_light_intensity():
    return analog_input.read()

def encode_morse_code(message):
    morse_code_signal = []
    for char in message:
        morse_code = morse_code_dict.get(char)
        if morse_code:
            morse_code_signal.extend(morse_code)
            morse_code_signal.append(' ')  # Gap between characters
    return morse_code_signal

def decode_morse_code(morse_code_signal):
    decoded_message = ""
    current_symbol = ""

    for signal in morse_code_signal:
        if signal == '.' or signal == '-':
            current_symbol += signal
        elif signal == ' ':
            char = None
            for key, value in morse_code_dict.items():
                if value == current_symbol:
                    char = key
                    break
            decoded_message += char if char else ' '
            current_symbol = ""
    return decoded_message

def main():
    user_input = input("Enter a message: ").upper()
    morse_code_signal = encode_morse_code(user_input)

    try:
        for signal in morse_code_signal:
            if signal == '.':
                board.digital[led_pin].write(1)
                time.sleep(0.3)
                board.digital[led_pin].write(0)
            elif signal == '-':
                board.digital[led_pin].write(1)
                time.sleep(0.9)
                board.digital[led_pin].write(0)
            elif signal == ' ':
                time.sleep(0.6)  # Gap between characters

            light_intensity = read_light_intensity()
            if light_intensity is not None:
                print("light intensity ==>", light_intensity)

            time.sleep(0.3)  # Gap between signals

        decoded_text = decode_morse_code(morse_code_signal)
        print("Decoded message:", decoded_text)

    except KeyboardInterrupt:
        board.digital[led_pin].write(0)
        board.exit()

if __name__ == "__main__":
    main()


from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.urls import reverse
import csv
from pagination.settings import BUS_STATION_CSV

def index(request):
    return redirect(reverse('bus_stations'))

def bus_stations(request):
    page_num = int(request.GET.get('page', 1))
    data = []
    with open(BUS_STATION_CSV, encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            data.append(row)
    paginator = Paginator(data, per_page=10)
    page = paginator.get_page(page_num)
    context = {
         'bus_stations': page,
         'page': page,
    }
    return render(request, 'stations/index.html', context)


from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con

def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)

time.sleep(2)

def freeze():
    counter = 1

    iml = pyautogui.screenshot(region=(1028,60,880,500))
    iml.save(r"C:\Users\JSP10\Desktop\Android bots\Autobot Python\Checking.png")

    print("I've taken a screenshot")

    while pyautogui.locateOnScreen('Checking.png', region=(1028,60,880,500)) != None:

          print("I can see Checking")
          counter = counter + 1
          print(counter)
          if counter == 300:
              click(1296,57)
              time.sleep(1)
              click(1658,183)
              time.sleep(1)
              click(1384,161)
              time.sleep(18)
              click(1384,161)
              while pyautogui.locateOnScreen('Resume.png', region=(1028,60,880,500)) == None:
                print("Waiting for Continue")
              else:
                    sleep(0.5)
                    print("clicked")
                    click(1537,448)

    else:

         print("Next")

    print("End")

while True:

    if pyautogui.locateOnScreen('GemLair.png', region=(1000,60,920,500),grayscale=True, confidence =0.95) != None:
        print("I can see GemLair")
        click(1699,442)

    elif pyautogui.locateOnScreen('Start.png', region=(1000,60,920,500),grayscale=True, confidence =0.95) != None:
        print("I can see start")
        click(1518,505)

    elif pyautogui.locateOnScreen('Done1.png', region=(1000,60,920,500),grayscale=True, confidence =0.95) != None:
        print("I can see Done1")
        click(1462,504)

    elif pyautogui.locateOnScreen('Done.png', region=(1000,60,920,500),grayscale=True, confidence =0.95) != None:
        print("I can see Done")
        click(1743,532)

    freeze()


from collections import Counter
from enum import Enum

from autonetkit.design.utils import filters
from autonetkit.network_model.network_model import NetworkModel
from autonetkit.network_model.port import Port
from autonetkit.network_model.topology import Topology
from autonetkit.network_model.types import DeviceType

def build_ip_base(network_model: NetworkModel, topology: Topology):
    """

    @param network_model:
    @param topology:
    """
    t_l2 = network_model.get_topology("layer2")
    topology.add_nodes_from(t_l2.nodes())
    topology.add_links_from(t_l2.links())

    bc_nodes = filters.broadcast_domains(topology)

    for node in bc_nodes:
        peers = node.peer_nodes()
        peer_asns = {n.get("asn") for n in peers}
        peer_types = {n.type for n in peers}
        if len(peer_asns) == 1:
            if peer_types == {DeviceType.ROUTER}:
                node.set("bc_type", IpBcTypes.BACKBONE)
            else:
                node.set("bc_type", IpBcTypes.HOSTS)

        else:
            node.set("bc_type", IpBcTypes.INTER_DOMAIN)

def allocate_asns(topology: Topology):
    """

    @param topology:
    """
    bc_nodes = filters.broadcast_domains(topology)

    for node in bc_nodes:
        peer_asns = sorted(n.get("asn") for n in node.peer_nodes())
        if len(set(peer_asns)) == 1:
            asn = peer_asns[0]
        else:
            counted = Counter(peer_asns)
            asn = counted.most_common(1)[0][0]
        node.set("asn", asn)

def _sort_ports_by_routers(port: Port):
    # sorts so that routers are allocated the first ip from block
    if port.node.type == DeviceType.ROUTER:
        return 1
    else:
        return 2

def map_blocks_to_ports(topology):
    """

    @param topology:
    """
    bc_nodes = filters.broadcast_domains(topology)
    for bc_node in bc_nodes:
        subnet = bc_node.get("network")
        hosts = subnet.hosts()
        ports = bc_node.peer_ports()
        ports = sorted(ports, key=lambda x: _sort_ports_by_routers(x))
        for peer_port in ports:
            peer_port.set("network", subnet)
            host_ip = next(hosts)
            peer_port.set("ip", host_ip)

class IpBcTypes(Enum):
    HOSTS = 1
    BACKBONE = 2
    INTER_DOMAIN = 3


import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# ------------------------------------------
# PIN NUMARALARI
# ------------------------------------------
TRIG = 23
ECHO = 24

print("HC-SR04 mesafe sensoru")

# ------------------------------------------
# GİRİŞ VE ÇIKIŞLARIN BELİRTİLMESİ
# ------------------------------------------
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)

# ------------------------------------------
# MESAFE ÖLÇÜMÜ
# ------------------------------------------
while True:
    # ölçme aralığı ve veri iletim hızı
    GPIO.output(TRIG, False)
    print("Olculuyor...")
    time.sleep(0.5)

    GPIO.output(TRIG, True)
    time.sleep(0.0001)
    GPIO.output(TRIG, False)

    while GPIO.input(ECHO) == 0:
        pulse_start = time.time()

    while GPIO.input(ECHO) == 1:
        pulse_end = time.time()

    pulse_duration = pulse_end - pulse_start

    distance = pulse_duration * 17150
    distance = round(distance, 2)

    # 2 ve 400 aralığındaki ölçümler yapılır onun dışında menzil aşıldı bilgisi verilir
    if distance > 2 and distance < 400:
        print("Mesafe:", distance - 0.5, "cm")
    else:
        print("Menzil asildi")


from hypothesis import given, assume, settings
import hypothesis.strategies as st
import pytest
import numpy as np

from latticegen.latticegeneration import *

@given(st.floats(0., exclude_min=True, allow_infinity=False),
       st.floats(0, np.pi),
       st.floats(1e-200, 10, exclude_min=True),
       st.floats(0, np.pi),
       st.integers(4, 7),
       )
def test_generate_ks(r, t, k, p, sym):
    assume(np.isfinite(r*np.pi*2))
    assume(r / (np.pi*2) > 0.0)
    ks = generate_ks(r, t, k, p, sym)
    assert ks.shape == (sym + 1, 2)
    assert ks.max() <= max(r / k, r)

@given(r=st.floats(1e-20, 1e8, exclude_min=True, allow_infinity=False),
       t=st.floats(0, np.pi),
       o=st.integers(1, 3),
       k=st.floats(0.001, 10, exclude_min=True),
       p=st.floats(0, np.pi),
       size=st.one_of([st.integers(2, 50),
                       st.tuples(st.integers(2, 50), st.integers(2, 50))]),
       )
def test_fast_gen(r, t, o, k, p, size):
    # Don't use more than float max periods.
    assume(np.isfinite(r*np.max(size)*np.pi*2))
    ref = hexlattice_gen(r, t, o, size, k, p)
    fast = hexlattice_gen_fast(r, t, o, size, k, p)
    assert fast.shape == ref.shape
    ref = ref.compute()
    fast = fast.compute()
    atol = max(4e-10*r, 1e-10)
    assert np.abs(ref - fast).max() < atol
    assert np.allclose(ref, fast, rtol=1e-5, atol=atol)

# @given(r=st.floats(1e-250, 1e250, allow_infinity=False),
#        t=st.floats(0, np.pi),
#        o=st.integers(1, 3),
#        k=st.floats(1e-10, 1e10, exclude_min=True),
#        p=st.floats(0, np.pi),
#        size=st.tuples(st.integers(2, 50), st.integers(2, 50)),
#        )
# def test_new_hex_gen(r, t, o, k, p, size):
#     # Don't use more than float max periods.
#     assume(np.isfinite(r*np.max(size)*np.pi*2))
#     ref = hexlattice_gen(r, t, o, size, k, p)
#     new = hexlattice_gen2(r, t, o, size, k, p)
#     assert new.shape == ref.shape
#     ref = ref.compute()
#     new = new.compute()
#     assert np.allclose(ref, new)

@given(r=st.floats(0.0, exclude_min=True, allow_infinity=False),
       t=st.floats(0, np.pi),
       o=st.integers(1, 3),
       k=st.floats(1e-6, 10, exclude_min=True),
       p=st.floats(0, np.pi),
       size=st.tuples(st.integers(2, 70),
                      st.integers(2, 70)),
       sym=st.integers(4, 7),
       norm=st.booleans()
       )
@pytest.mark.filterwarnings("ignore:invalid value")
def test_gen(r, t, o, sym, k, p, size, norm):
    # Don't use more than float max periods.
    assume(np.isfinite(r*max(size)*np.pi*2))
    ref = anylattice_gen(r, t, o, sym, size, k, p, normalize=norm)
    assert ref.shape == size
    ref = ref.compute()
    assert np.all(~np.isnan(ref))
    if norm:
        assert np.all(ref <= 1.0)
        assert np.all(ref >= 0.0)

@given(st.integers(3, 500))
def test_shapes_square(s):
    assert hexlattice_gen(0.1, 0., 1, s).shape == (s, s)
    assert anylattice_gen(0.1, 0., 1, 4, s).shape == (s, s)


import sys
#import os
from PyQt4 import QtGui, QtCore
#from PyQt4.QtCore import*
#from PyQt4.QtGui import*
#from ProjectHandler import ProjectHandler

class SettingsWin(QtGui.QMainWindow):
    #set signals
    onEmptyField = QtCore.pyqtSignal()
    onData       = QtCore.pyqtSignal()

    def __init__(self,ProjectHandler):
        super(SettingsWin, self).__init__()
        self.PH = ProjectHandler
        #get screen size
        self.screen_h = self.PH.settings['res']['width']
        self.screen_v = self.PH.settings['res']['height']
        #set relative size
        self.r_size = 0.7
        self.init_ui()
        #settings dict
        self.inf_settings = {"imu_port"    : None,
                             "imu_sample"  : None,
                             "laser_port"  : None,
                             "laser_sample": None,
                             "ecg_port"    : None,
                             "ecg_sample"  : None,
                             "IpRobot"     : None}

    def init_ui(self):
        self.setWindowTitle('Setting')
        self.winsize_h=int(self.screen_h * self.r_size)
        self.winsize_v=int(self.screen_v* self.r_size)
        self.setGeometry(self.screen_h / 2 - (self.winsize_h / 2), self.screen_v / 2 - (self.winsize_v / 2), self.winsize_h, self.winsize_v)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        ## background label
        self.label_background = QtGui.QLabel(self)
        self.label_background.setGeometry(QtCore.QRect(0, 0, self.winsize_h, self.winsize_v))
        self.label_background.setPixmap(QtGui.QPixmap(self.PH.paths["img"] + "Settings_background.png"))
        self.label_background.setScaledContents(True)
        #buttons dict
        self.ControlButtons = {}
        #apply changes button
        self.ControlButtons['apply'] = QtGui.QCommandLinkButton(self)
        self.ControlButtons['apply'].setGeometry(QtCore.QRect(self.winsize_h*0.75, self.winsize_v*0.85, self.winsize_v*0.17, self.winsize_h*0.05))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(self.PH.paths["img"] + "aply_settings.png"),QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ControlButtons['apply'].setIcon(icon)
        self.ControlButtons['apply'].setIconSize(QtCore.QSize(self.winsize_v * 0.16, self.winsize_h * 0.04))

        #cancel button
        self.ControlButtons['cancel'] = QtGui.QCommandLinkButton(self)
        self.ControlButtons['cancel'].setGeometry(QtCore.QRect(self.winsize_h*0.85, self.winsize_v*0.85, self.winsize_v*0.17, self.winsize_h*0.05))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(self.PH.paths["img"] + "cancel_settings.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ControlButtons['cancel'].setIcon(icon)
        self.ControlButtons['cancel'].setIconSize(QtCore.QSize(self.winsize_v * 0.16, self.winsize_h * 0.04))

        #memory button
        self.ControlButtons['clearMemoryBN'] =  QtGui.QCommandLinkButton(self)
        self.ControlButtons['clearMemoryBN'].setGeometry(QtCore.QRect(self.winsize_h*0.65, self.winsize_v*0.85, self.winsize_v*0.17, self.winsize_h*0.05))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(self.PH.paths["img"] + "delete_memory.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ControlButtons['clearMemoryBN'].setIcon(icon)
        self.ControlButtons['clearMemoryBN'].setIconSize(QtCore.QSize(self.winsize_v * 0.16, self.winsize_h * 0.04))

        #clear db button
        #memory button
        self.ControlButtons['clear_db'] =  QtGui.QCommandLinkButton(self)
        self.ControlButtons['clear_db'].setGeometry(QtCore.QRect(self.winsize_h*0.55, self.winsize_v*0.85, self.winsize_v*0.17, self.winsize_h*0.05))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(self.PH.paths["img"] + "delete_db.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ControlButtons['clear_db'].setIcon(icon)
        self.ControlButtons['clear_db'].setIconSize(QtCore.QSize(self.winsize_v * 0.16, self.winsize_h * 0.04))

        # close button
        self.CloseButton = QtGui.QCommandLinkButton(self)
        self.CloseButton.setGeometry(QtCore.QRect(self.winsize_h * 0.95, self.winsize_v * 0.01, self.winsize_v * 0.045, self.winsize_h * 0.03))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(self.PH.paths["img"] + "exit_icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.CloseButton.setIcon(icon)
        self.CloseButton.setIconSize(QtCore.QSize(self.winsize_v * 0.4, self.winsize_h * 0.02))
        #
        self.laser_port = QtGui.QLineEdit(self)
        self.laser_port.setGeometry(QtCore.QRect(self.winsize_h * 0.33, self.winsize_v * 0.47, self.winsize_h * 0.1, self.winsize_v * 0.04))

        self.imu_port = QtGui.QLineEdit(self)
        self.imu_port.setGeometry(QtCore.QRect(self.winsize_h * 0.67, self.winsize_v * 0.255, self.winsize_h * 0.1, self.winsize_v * 0.04))

        self.ecg_port = QtGui.QLineEdit(self)
        self.ecg_port.setGeometry(QtCore.QRect(self.winsize_h * 0.6, self.winsize_v * 0.61, self.winsize_h * 0.1, self.winsize_v * 0.04))

        self.laser_sample = QtGui.QLineEdit(self)
        self.laser_sample.setGeometry(QtCore.QRect(self.winsize_h * 0.33, self.winsize_v * 0.53, self.winsize_h * 0.1, self.winsize_v * 0.04))

        self.imu_sample = QtGui.QLineEdit(self)
        self.imu_sample.setGeometry(QtCore.QRect(self.winsize_h * 0.67, self.winsize_v * 0.32, self.winsize_h * 0.1, self.winsize_v * 0.04))

        self.ecg_sample = QtGui.QLineEdit(self)
        self.ecg_sample.setGeometry(QtCore.QRect(self.winsize_h * 0.6, self.winsize_v * 0.66, self.winsize_h * 0.1, self.winsize_v * 0.04))

        self.id_robot = QtGui.QLineEdit(self)
        self.id_robot.setGeometry(QtCore.QRect(self.winsize_h * 0.285, self.winsize_v * 0.32, self.winsize_h * 0.12, self.winsize_v * 0.04))

        #set internal signals
        self.set_signals()

    #set internal signals method
    def set_signals(self):
        self.ControlButtons['apply'].clicked.connect(self.apply_button)
        self.onData.connect(self.close)

    #method called when apply button is pressed
    def apply_button(self):
        if not (self.laser_port.text() == '') and not (self.imu_port.text() == '') and not (self.ecg_port.text() == '') and not (self.laser_sample.text() == '') and not (self.imu_sample.text() == '') and not (self.ecg_sample.text() == '') and not (self.id_robot.text() == ''):
            self.inf_settings['laser_port'] = str(self.laser_port.text())
            self.inf_settings['imu_port'] = str(self.imu_port.text())
            self.inf_settings['ecg_port'] = str(self.ecg_port.text())
            self.inf_settings['laser_sample'] = str(self.laser_sample.text())
            self.inf_settings['imu_sample'] = str(self.imu_sample.text())
            self.inf_settings['ecg_sample'] = str(self.ecg_sample.text())
            self.inf_settings['IpRobot'] = str(self.id_robot.text())
            #emit signal on data received
            self.onData.emit()
        else:
            #emit signal on empty field left
            self.onEmptyField.emit()

def main():
    app = QtGui.QApplication(sys.argv)
    GUI = SettingsWin(ProjectHandler())
    GUI.show()
    sys.exit(app.exec_())
if __name__ == '__main__':
    main()