pourquoi mon objectif de pas marche pas: 

# importation des bibliothèques kivy (pour interface), plyer (pour accelerometre) et math
from kivy.clock import Clock
import math
from plyer import accelerometer
from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.utils import platform
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.popup import Popup
from kivy.uix.image import Image
from kivy.uix.widget import Widget
import sqlite3
import datetime
from kivymd.uix.label import MDLabel
from kivymd.uix.floatlayout import MDFloatLayout

KV = """
<SocialScreen>:
    name: 'social'

<SettingsScreen>:
    name: 'settings'
    MDLabel:
        text: 'Settings Screen'
        halign: 'center'
        valign: 'middle'
    MDLabel:
        id: poids
        text:'Nouveau poids ?'
        font_size: "20sp"
        pos_hint:{"center_x":0.6,"center_y":0.7}
        text_color: 0, 0, 0, 1
    MDLabel:
        id: taille
        text:'Nouvelle taille ?'
        font_size: "20sp"
        pos_hint:{"center_x":0.6,"center_y":0.62}
        text_color: 0, 0, 0, 1
    TextInput:
        id : new_poids
        halign:'center'
        font_size: "20sp"
        hint_text: '--- kg'
        size_hint: None,None
        size: (220,60)
        pos_hint: {"center_x":0.72,"center_y":0.7}
    TextInput:
        id : new_taille
        halign:'center'
        font_size: "20sp"
        hint_text: '--- cm'
        size_hint: None,None
        size: (220,60)
        pos_hint: {"center_x":0.72,"center_y":0.62}
    MDIconButton:
        icon:"checkbox-marked"
        pos_hint:{"center_x": 0.93,"center_y":0.62}
        icon_size:dp(38)
        on_press: root.nouv_taille(self.parent.children[5].text)     

    MDIconButton:
        icon:"checkbox-marked"
        pos_hint:{"center_x": 0.93,"center_y":0.7}
        icon_size:dp(38)   
        on_press: root.nouv_poids(self.parent.children[6].text)     

<AccelerometerScreen>:
    name: 'accelerometer'
    MDBottomNavigation:
        panel_color: 0, 0, 0, 0
        text_color_active: 0, 0, 0, 1

        MDBottomNavigationItem:

            icon: 'home'
            id: home
            MDLabel:
                id: label_home
                halign: 'center'
                theme_text_color: "Custom"
                text_color: 1, 0, 1, 1
                markup: True

                canvas.before:
                    Color:
                        rgba: 0, 1, 0, 1  # Couleur du cercle (vert ici)
                    Line:
                        circle: (self.center_x, self.center_y, self.width/3)
                        width: 6

        MDBottomNavigationItem:
            name: 'score'
            icon: 'trophy-outline'
            MDLabel:
                halign: 'center'


        MDBottomNavigationItem:
            name: 'social'
            id: social
            icon: 'chat-processing'
            FloatLayout:
                ScrollView:
                    id: scroll  
                    size_hint:(0.8,0.45)
                    pos_hint:{"center_x":0.5,"center_y":0.28}
                    bar_color:0,1,0,1
                    bar_width:10
                    spacing:70
                    canvas.before:
                        Color:
                    	    rgba:0.9,0.9,0.9,1
                        Rectangle:
                            pos: self.pos
                            size: self.size
                    BoxLayout:
                    	id: box
                    	orientation:'vertical'
                    	size_hint_y:None
                    	height:200


            MDFloatLayout:
                orientation: 'vertical'
                spacing: 10
                padding: 40
                MDLabel:
                	text:"Découvrez le nombre de pas de vos amis \\net tentez de les devancer !"
                	pos_hint: {"center_x":0.6,"center_y":0.65}

                MDLabel:
                    halign: 'center'
                    text: 'Social'
                    bold: True
                    pos_hint: {"center_x":0.5,"center_y":0.89}
                    font_size:"50sp"
                TextInput:
                    id : amis
                    halign:'left'
                    valign:'center'
                    font_size: "25sp"
                    hint_text: 'Rechercher des amis'
                    size_hint: (0.67,0.10)
                    pos_hint: {"center_x":0.41,"center_y":0.76}
                MDIconButton:

                    icon:"magnify"
                    icon_size:"80sp"
                    size_hint: None,None
                    size: (120,120)
                    pos_hint: {"center_x":0.87,"center_y":0.76}

                    on_press: app.social_instance.chercher_ami(self.parent.children[2].text)
                MDLabel:
                    halign: 'center'
                    text: 'Amis:'

                    pos_hint: {"center_x":0.2,"center_y":0.55}
                    font_size:"30sp"



        MDBottomNavigationItem:
            name: 'profile'
            icon: 'cellphone-key'

            MDFloatLayout:
                MDLabel:
                    canvas.before:
                        Color:
                            rgba:1,1,1,1
                        Rectangle:
                            pos:0,0
                            size: 100000,100000
                MDLabel:
                    canvas.before:
                        Color:
                	        rgba:0,0,0,1
                        Rectangle:
                            pos:0,root.height*0.73
                            size: root.width,root.width
                MDLabel:
                    canvas.before:
                        Color:
                	        rgba:0,0,0,1
                        Ellipse:
                            pos:-0.35*root.width,root.height*0.69
                            size: root.width*1.2,root.width*1.2
                MDLabel:
                    canvas.before:
                        Color:
                	        rgba:1,1,1,1
                        Ellipse:
                            pos:root.width*0.45,root.height*0.57
                            size: root.width*0.8,root.width*0.4
                MDLabel:
                    canvas.before:
                        Color:
                            rgba:0.5,0.5,0.5,1
                        Line:
                        	points:[self.width*0.02,self.height/1.8,self.width*0.98,self.height/1.8]
                        	width:2
                MDLabel:
                	id: pas_tot
                	text:"test"
                	text_color:0,0,0,1
                	pos_hint:{"center_x":0.6,"center_y":0.49}
                	font_size:"20sp"
                MDLabel:
                    canvas.before:
                        Color:
                            rgba:0.5,0.5,0.5,1
                        Line:
                            points:[self.width*0.02,self.height/2.4,self.width*0.98,self.height/2.4]
                            width:2
                MDLabel:
                	id: pseudo
                	text:"Votre pseudo"
                	text_color: 0,1,0,1
                	font_size:"34sp"
                	pos_hint:{"center_x":0.6,"center_y":0.92}
                MDIconButton:
                    icon: "cog"
                    pos_hint: {"top": 1,"right":1}
                    theme_icon_color: "Custom"
                    icon_color: 1,1,1,1
                    on_release: app.root.current = 'settings'

                MDLabel:
                    id: imc_label
                    halign: 'center'
                    valign: 'middle'
                    text: ''
                    font_style: 'H5'
                    size_hint_y: 0.5
                    pos_hint:{"center_x":0.25,"center_y":0.65}
                    theme_text_color: "Custom"
                    text_color: 0, 0, 0, 1
                MDLabel:
                    id: imc_info_label
                    halign: 'center'
                    valign: 'middle'
                    text: ''
                    size_hint_y: 0.5
                    pos_hint:{"center_x":0.45,"center_y":0.6}
                    theme_text_color: "Custom"
                    text_color: 0, 0, 0, 1

                MDTextField:
                    id: daily_goal_input
                    hint_text: "Nouvel objectif de pas quotidien"
                    halign:"center"
                    helper_text: "Entrez le nouvel objectif de pas quotidien"
                    helper_text_mode: "on_focus"
                    pos_hint: {"center_x": 0.4, "center_y": 0.35}
                    size_hint_x: None
                    width: 460
                MDRaisedButton:
                    text: "Valider"
                    pos_hint: {"center_x": 0.85, "center_y": 0.35}
                    on_release: app.set_daily_goal(daily_goal_input.text)


<LoginScreen>:
    name: 'login'
    BoxLayout:
        orientation: 'vertical'
        spacing: 10
        padding: 40

<RegisterScreen>:
    name: 'register'
    BoxLayout:
        orientation: 'vertical'
        spacing: 10
        padding: 40
        Label:
            text: 'Pseudo'
        Label:
            text: 'Mot de passe'
        Label:
            text: 'Confirmez le mot de passe'
        Label:
            text: 'Taille'
        Label:
            text: 'Poids'
"""


class ProfileScreen(MDScreen):
    def __init__(self, db, **kwargs):
        super(ProfileScreen, self).__init__(**kwargs)
        self.db = db

        self.objectif_input = TextInput(multiline=False, hint_text="Objectif de pas", height=hauteur_ecran * 0.08,
                                        size_hint_y=None)
        self.add_widget(self.objectif_input)

        objectif_input = self.objectif_input

        save_button = Button(text='Enregistrer', on_press=self.save_objectif)
        self.add_widget(save_button)

    def save_objectif(self, instance):
        new_objectif = self.objectif_input.text
        user = self.db.get_user_by_pseudo(self.manager.get_screen('login').pseudo_input.text)
        if user:
            user_id = user[0]
            self.db.update_objectif(user_id, new_objectif)
            self.objectif_input.text = ""

            self.update_objectif_label(new_objectif)

    def update_objectif_label(self, objectif):
        # Mettez à jour l'affichage de l'objectif de pas dans votre interface utilisateur
        pass



class SettingsScreen(MDScreen):
    def __init__(self, **kwargs):
        super(SettingsScreen, self).__init__(**kwargs)
        self.orientation = 'vertical'

        # Bouton de retour
        self.back_button = Button(text="Retour", size_hint=(None, None), size=(200, 50), pos_hint={'x': 0, 'y': 0})
        self.back_button.bind(on_press=self.go_back)
        self.add_widget(self.back_button)

        # BoxLayout pour centrer le bouton supprimer données
        layout = BoxLayout(orientation='vertical', spacing=20)
        self.add_widget(layout)

        # Bouton de suppression des données
        self.delete_data_button = Button(text="Supprimer mes données", size_hint=(None, None), size=(350, 50),
                                         pos_hint={'center_x': 0.5})
        self.delete_data_button.bind(on_press=self.confirm_delete_data)
        self.delete_data_button.background_color = (1, 0, 0, 1)  # Couleur rouge
        layout.add_widget(Widget())  # Espace pour centrer verticalement
        layout.add_widget(self.delete_data_button)
        layout.add_widget(Widget())  # Espace pour centrer verticalement

        self.logout_button = Button(text="Déconnexion", size_hint=(None, None), size=(200, 50),
                                    pos_hint={'center_x': 0.5, 'center_y': 0.42})
        self.logout_button.bind(on_press=self.logout)
        self.add_widget(self.logout_button)

    def nouv_poids(self, poids):
        pseudo = self.manager.get_screen('login').pseudo_input.text
        db = self.manager.get_screen('login').db
        user = db.get_user_by_pseudo(pseudo)
        db.cursor.execute("UPDATE users SET poids=? WHERE pseudo=?", (poids, pseudo))
        db.conn.commit()
        self.ids.new_poids.text = ""

    def nouv_taille(self, taille):
        pseudo = self.manager.get_screen('login').pseudo_input.text
        db = self.manager.get_screen('login').db
        user = db.get_user_by_pseudo(pseudo)
        db.cursor.execute("UPDATE users SET taille=? WHERE pseudo=?", (taille, pseudo))
        db.conn.commit()
        self.ids.new_taille.text = ""

    def go_back(self, instance):
        # Cette fonction change l'écran actuel pour l'écran 'profile' (ou un autre écran de votre choix)
        self.manager.current = 'home'

    def confirm_delete_data(self, instance):
        # Afficher une boîte de dialogue de confirmation
        confirm_popup = ConfirmationPopup(delete_function=self.delete_data)
        confirm_popup.open()

    def delete_data(self):
        # Cette fonction supprime les donnÃ©es de l'utilisateur et redirige vers l'Ã©cran d'inscription
        pseudo = self.manager.get_screen('login').pseudo_input.text
        db = self.manager.get_screen('login').db
        user = db.get_user_by_pseudo(pseudo)
        if user:
            user_id = user[0]
            db.cursor.execute('DELETE FROM steps WHERE user_id=?', (user_id,))
            db.cursor.execute('DELETE FROM users WHERE id=?', (user_id,))
            db.conn.commit()
            self.manager.get_screen('login').pseudo_input.text = ""  # pour effacer l'pseudo dans le champ d'inscription

            self.manager.current = 'register'

    def logout(self, instance):
        self.manager.current = 'login'


class ConfirmationPopup(Popup):
    def __init__(self, delete_function, **kwargs):
        super(ConfirmationPopup, self).__init__(**kwargs)
        self.title = "Confirmation"
        self.size_hint = (None, None)
        self.size = (700, 300)
        self.auto_dismiss = False

        content = BoxLayout(orientation='vertical', spacing=30, padding=20)
        content.add_widget(Label(text="Êtes-vous sûr de vouloir supprimer vos données ?"))
        buttons_layout = BoxLayout(spacing=10)

        cancel_button = Button(text="Annuler", on_press=self.dismiss)
        confirm_button = Button(text="Confirmer", on_press=lambda _: self.confirm_delete(delete_function))

        buttons_layout.add_widget(cancel_button)
        buttons_layout.add_widget(confirm_button)

        content.add_widget(buttons_layout)

        self.content = content

    def confirm_delete(self, delete_function):
        delete_function()
        self.dismiss()


# def get_friends_by_user_id(self, user_id):
#    self.cursor.execute('SELECT * FROM friends WHERE user_id=?', (user_id,))
#    return self.cursor.fetchall()
class ScoreScreen(MDScreen):
    def __init__(self, db, **kwargs):
        super(ScoreScreen, self).__init__(**kwargs)
        self.db = db
        self.conn = sqlite3.connect("base_de_donnees.db")
        self.cursor = self.conn.cursor()

        layout = BoxLayout(orientation='vertical', spacing=10, padding=40)
        self.add_widget(layout)

        self.title_label = Label(text='Score', halign='center', color=(0, 0, 0, 1), size_hint=(None, None),
                                 pos_hint={"center_x": 0.5, "center_y": 0.3}, font_size="50sp", bold=True)
        layout.add_widget(self.title_label)

        self.add_users_to_score_tab()

    def add_users_to_score_tab(self):
        users = self.db.get_all_users_with_steps()
        users_sorted = sorted(users, key=lambda x: x[1], reverse=True)  # Tri par ordre décroissant de pas

        for user in users_sorted:
            pseudo_label = Label(text=f"{user[0]} - Pas: {user[1]}", halign='center', color=(0, 0, 0, 1))
            self.add_widget(pseudo_label)


class SocialScreen(MDScreen):
    def __init__(self, accelerometer_instance, db, **kwargs):
        super(SocialScreen, self).__init__(**kwargs)
        self.accelerometer_instance = accelerometer_instance
        self.db = db
        self.conn = sqlite3.connect("base_de_donnees.db")
        self.cursor = self.conn.cursor()
        layout = MDFloatLayout(orientation='vertical', spacing=10, padding=40)
        self.add_widget(layout)
        self.social = MDLabel(text='Social', halign='center', color=(0, 0, 0, 1),
                              pos_hint={'center_x': 0.5, 'center_y': 0.85}, font_size="50sp", bold=True)
        layout.add_widget(self.social)
        self.notification_popup = NotificationPopup(title='', size_hint=(None, None), size=(largeur_ecran * 0.7, 200))

    def show_notification(self, text):
        self.notification_popup.content.text = text
        self.notification_popup.open()

    def chercher_ami(self, user_input):
        app = MDApp.get_running_app()

        user_trouver = self.cursor.execute("SELECT * FROM users WHERE pseudo=?", (user_input,)).fetchall()
        if user_trouver:
            confirmer_ami = AmiTrouverPopup(user_trouver[0][1])
            confirmer_ami.open()


class AmiTrouverPopup(Popup):
    def __init__(self, pseudo, **kwargs):
        super().__init__(**kwargs)
        self.title = "Utilisateur trouver!"
        self.size_hint = (None, None)
        self.size = (700, 300)
        self.auto_dismiss = False
        self.db = Database()
        self.pseudo = pseudo
        app = MDApp.get_running_app()
        self.conn = sqlite3.connect("base_de_donnees.db")
        self.cursor = self.conn.cursor()
        content = BoxLayout(orientation='vertical', spacing=30, padding=20)
        content.add_widget(Label(text="Voulez-vous ajouter cet utilisateur \n à votre liste d'ami ?"))
        buttons_layout = BoxLayout(spacing=10)

        cancel_button = Button(text="Annuler", on_press=self.dismiss)
        confirm_button = Button(text="Ajouter", on_press=lambda x: app.accelerometer_instance.ajout_ami(self.pseudo))
        buttons_layout.add_widget(cancel_button)
        buttons_layout.add_widget(confirm_button)

        content.add_widget(buttons_layout)

        self.content = content


class LoginScreen(Screen):
    def __init__(self, db, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.db = db
        self.conn = sqlite3.connect("base_de_donnees.db")
        self.cursor = self.conn.cursor()
        self.pseudo_stock = ""
        layout = BoxLayout(orientation='vertical', spacing=10, padding=40)
        self.add_widget(layout)

        self.logo = Image(source='logo.jpg', size_hint=(1, 1), allow_stretch=True)
        layout.add_widget(self.logo)

        pseudo_label = Label(text='pseudo:', halign='left', color=(0, 0, 0, 1),
                             pos_hint={"center_x": 0.28}, font_size="20sp")
        self.pseudo_input = TextInput(multiline=False, hint_text="nom d'utilisateur", height=hauteur_ecran * 0.12,
                                      font_size="20sp", size_hint_y=None, )
        layout.add_widget(pseudo_label)
        layout.add_widget(self.pseudo_input)

        password_label = Label(text='mot de passe:', halign='center', pos_hint={"center_x": 0.37},
                               color=(0, 0, 0, 1), font_size="20sp")
        self.password_input = TextInput(password=True, multiline=False, hint_text="mot de passe",
                                        height=hauteur_ecran * 0.12, font_size="20sp", size_hint_y=None)
        layout.add_widget(password_label)
        layout.add_widget(self.password_input)

        login_button = Button(text='Connexion', on_press=self.login, size_hint=(None, None), size=(200, 50))
        layout.add_widget(login_button)

        register_button = Button(text="Inscription", on_press=self.switch_to_register, size_hint=(None, None),
                                 size=(300, 50))
        layout.add_widget(register_button)

        self.notification_popup = NotificationPopup(title='', size_hint=(None, None), size=(largeur_ecran * 0.7, 200))

    def update_steps_label(self):
        user = self.db.get_user_by_pseudo(self.pseudo_input.text)
        if user:
            user_id = user[0]
            steps = self.db.get_steps_by_user_id(user_id)
            if steps:
                self.manager.get_screen('home').update_steps_label(steps[0])

    def login(self, instance):
        pseudo = self.pseudo_input.text
        password = self.password_input.text
        user = self.db.get_user_by_pseudo(pseudo)
        current_date = datetime.datetime.now().strftime("%Y-%m-%d")
        app = MDApp.get_running_app()
        if user and user[2] == password:
            self.cursor.execute('UPDATE steps SET connexion=connexion+1 WHERE user_id=? AND date=?',
                                (user[0], current_date))

            self.conn.commit()
            self.cursor.execute('UPDATE users SET debug=2 WHERE pseudo=?', (pseudo,))
            self.conn.commit()
            app.accelerometer_instance.ids.pseudo.text = pseudo

            self.update_steps_label()  # Mettre à jour les pas après la connexion
            self.manager.current = 'home'
            self.manager.get_screen('home').do_toggle()
        else:
            self.show_notification("Erreur de connexion, pensez Ã  vous inscrire !")

    def switch_to_register(self, instance):
        self.manager.current = 'register'

    def show_notification(self, text):
        self.notification_popup.content.text = text
        self.notification_popup.open()


class RegisterScreen(Screen):
    def __init__(self, db, **kwargs):
        super(RegisterScreen, self).__init__(**kwargs)
        self.db = db
        self.notification_popup = NotificationPopup(title='', size_hint=(None, None), size=(largeur_ecran * 0.7, 200))
        layout = BoxLayout(orientation='vertical', spacing=10, padding=40)
        self.add_widget(layout)
        self.stock_pseudo = None
        layout.add_widget(Label(text='Pseudo', color=(0, 0, 0, 1)))
        self.pseudo_input = TextInput(multiline=False)
        layout.add_widget(self.pseudo_input)

        layout.add_widget(Label(text='Mot de passe', color=(0, 0, 0, 1)))
        self.mdp_input = TextInput(password=True, multiline=False)
        layout.add_widget(self.mdp_input)

        layout.add_widget(Label(text='Confirmez le mot de passe', color=(0, 0, 0, 1)))
        self.confirm_mdp_input = TextInput(password=True, multiline=False)
        layout.add_widget(self.confirm_mdp_input)

        layout.add_widget(Label(text='Taille (cm)', color=(0, 0, 0, 1)))
        self.taille_input = TextInput(multiline=False)
        layout.add_widget(self.taille_input)

        layout.add_widget(Label(text='Poids (kg)', color=(0, 0, 0, 1)))
        self.poids_input = TextInput(multiline=False)
        layout.add_widget(self.poids_input)

        register_button = Button(text='S\'inscrire', on_press=self.register)
        layout.add_widget(register_button)

        back_button = Button(text='Retour', on_press=self.switch_to_login)
        layout.add_widget(back_button)

    def switch_to_login(self, instance):
        self.manager.current = 'login'

    def register(self, instance):
        pseudo = self.pseudo_input.text
        mdp = self.mdp_input.text
        confirm_mdp = self.confirm_mdp_input.text
        taille = self.taille_input.text
        poids = self.poids_input.text
        if len(pseudo) < 3 or len(pseudo) > 15:
            self.show_notification("Veuillez entrer un nom d'utilisateur \n entre 3 et 15 charactères.")
        elif not taille.isdigit() or not poids.isdigit() or mdp is "":
            self.show_notification("Veuillez remplir correctement toutes les cases.")
        elif mdp == confirm_mdp:
            self.db.create_user(pseudo, mdp, taille, poids)

            self.switch_to_login(instance)
            # self.manager.get_screen('home').do_toggle() #ENLEVER COMMENTAIRE SI LE COMPTEUR DE PAS NE FONCTIONNE PAS APRES INSCRIPTION (pas tester)
            self.show_notification(f"Inscription réussie pour {pseudo}")
        else:
            self.show_notification("Le mot de passe et la confirmation du mot de passe ne correspondent pas.")

    def show_notification(self, text):
        self.notification_popup.content.text = text
        self.notification_popup.open()


class Database:
    def __init__(self):
        self.conn = sqlite3.connect("base_de_donnees.db")
        self.cursor = self.conn.cursor()

        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                pseudo TEXT,
                mdp TEXT,
                taille INTEGER,
                poids INTEGER,
                debug INTEGER DEFAULT 0
            )
        ''')
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS steps (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                steps INTEGER,
                date TEXT,
                connexion INTEGER,
                objectif_pas INTEGER DEFAULT 0,
                FOREIGN KEY (user_id) REFERENCES users(id)
            )
        ''')
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS
amis (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER,
                pseudo_ami TEXT,
                friend_id INTEGER,
                pas_ami INTEGER,
                FOREIGN KEY (user_id)
REFERENCES users(id)           

            )
        ''')
        self.conn.commit()

    def get_all_users_with_steps(self):
        self.cursor.execute(
            "SELECT pseudo, steps FROM users join steps ON users.id = steps.id")  # erreur apparait a partir dici
        return self.cursor.fetchall()

    def reset_steps_daily(self, user_id):
        # Reset the steps count for the given user to 0

        current_date = datetime.datetime.now().strftime("%Y-%m-%d")

        self.cursor.execute('INSERT INTO steps (user_id,steps,date,connexion, objectif_pas) VALUES (?,?,?,?,0)',
                            (user_id, 0, current_date, 0))
        self.conn.commit()

    def create_user(self, pseudo, mdp, taille, poids):
        self.cursor.execute('''
            INSERT INTO users (pseudo, mdp, taille, poids, debug)
            VALUES (?, ?, ?, ?, ?)
        ''', (pseudo, mdp, taille, poids, 0))
        self.conn.commit()

    def get_user_by_pseudo(self, pseudo):
        self.cursor.execute('SELECT * FROM users WHERE pseudo=?', (pseudo,))
        return self.cursor.fetchone()

    def record_steps(self, user_id, steps):
        current_date = datetime.datetime.now().strftime("%Y-%m-%d")
        existing_steps = self.cursor.execute('SELECT steps FROM steps WHERE user_id=?', (user_id,)).fetchone()
        if existing_steps:
            self.cursor.execute('UPDATE steps SET steps=? WHERE user_id=? AND date=?', (steps, user_id, current_date))
        else:
            self.cursor.execute('INSERT INTO steps (user_id, steps, date,connexion, objectif_pas) VALUES (?, ?, ?, ?, 0)',
                                (user_id, steps, current_date, 1))
        self.conn.commit()

    def get_steps_by_user_id(self, user_id):
        current_date = datetime.datetime.now().strftime("%Y-%m-%d")
        self.cursor.execute('SELECT steps FROM steps WHERE user_id=? AND date=?', (user_id, current_date))
        return self.cursor.fetchone()


class NotificationPopup(Popup):
    def __init__(self, **kwargs):
        super(NotificationPopup, self).__init__(**kwargs)
        self.content = Label(text='', halign='center', valign='middle')

    def on_open(self):
        self.content.text_size = (self.width - 20, None)
        self.content.text = self.title + '\n' + self.content.text


def calculer_norme(x, y, z):
    # Cette fonction sert à calculer la norme, (valeur qui servira à determiner si un pas est comptabilisé ou non)
    # en fonction des valeurs x, y et z de l'accélérometre
    return math.sqrt(x ** 2 + y ** 2 + z ** 2)


def detecter_pas(x, y, z, derniere_norme, seuil_adaptable):
    # Cette fonction sert a calculer la difference entre la norme actuelle
    # et la dernière norme (avant l'actualisation du code)
    global difference
    norme = calculer_norme(x, y, z)
    difference = norme - derniere_norme

    if 10 > difference >= seuil_adaptable * 0.65:  # si cette difference est au dessus
        # de 0.65 fois le seuil, la fonction renvoie Vrai
        return True
    return False


def calcul_imc(masse, taille):
    return masse / (taille ** 2)


class AccelerometerScreen(MDScreen):
    def __init__(self, db):
        super().__init__(name="home")
        app = MDApp.get_running_app()

        self.db = db
        self.sensorEnabled = False
        self.derniere_norme = 0
        self.seuil_adaptable = 5
        self.somme = 1.5
        self.nbr_pas = 0
        self.pas_hier = 0
        self.pseudo = None

        self.debug = True
        self.debug_2 = True
        self.label_objectif = Label(text="Chargement...", halign="center", pos_hint={'center_x': 0.5, 'y': -0.33},
                                    font_size="35sp", color=(0, 0, 0, 1))
        self.ids.home.add_widget(self.label_objectif)
        self.label_der_pas = Label(text="Nombre de pas hier: 0", halign="center", pos_hint={'center_y': 0.4},
                                   font_size="10sp", color=(0, 0, 0, 1))
        self.ids.home.add_widget(self.label_der_pas)

        self.conn = sqlite3.connect("base_de_donnees.db")
        self.cursor = self.conn.cursor()

        self.pas_valide = 0
        self.label_pas = Label(text="0", halign="center", font_size="50sp", color=(0, 0, 0, 1))

        self.ids.home.add_widget(self.label_pas)

        self.do_toggle()

    def do_toggle(self):
        try:
            if not self.sensorEnabled and self.manager:
                home_screen = self.manager.get_screen('home')
                if home_screen == self:
                    accelerometer.enable()
                    Clock.schedule_interval(self.get_acceleration, 1 / 4.)
                    self.sensorEnabled = True
        except NotImplementedError:
            import traceback
            traceback.print_exc()
            status = "Accelerometer is not implemented for your platform"

    def update_steps_label(self, steps):
        self.nbr_pas = steps
        self.label_pas.text = str(self.nbr_pas)
        self.derniere_norme = 0

    def ajout_ami(self, pseudo_ami):
        current_date = datetime.datetime.now().strftime("%Y-%m-%d")
        self.pseudo = self.ids.pseudo.text
        user_id = self.cursor.execute("SELECT id FROM users WHERE pseudo=?", (self.pseudo,)).fetchone()
        user_id = user_id[0]
        friend_id = self.cursor.execute("SELECT id FROM users WHERE pseudo=?", (pseudo_ami,)).fetchone()
        friend_id = friend_id[0]
        friend_pas = self.cursor.execute("SELECT steps FROM steps WHERE user_id=? AND date=?",
                                         (friend_id, current_date)).fetchone()
        if friend_pas:
            friend_pas = friend_pas[0]
        else:
            friend_pas = 0
        ami_existe = self.cursor.execute("SELECT friend_id FROM amis WHERE pseudo_ami=?", (pseudo_ami,)).fetchone()
        if ami_existe:
            ami_existe = ami_existe[0]
        if ami_existe == friend_id:
            pass
        else:
            self.cursor.execute("INSERT INTO amis (user_id,pseudo_ami,friend_id,pas_ami) VALUES (?,?,?,?)",
                                (user_id, pseudo_ami, friend_id, friend_pas))
            self.conn.commit()
            self.cursor.execute('UPDATE users SET debug=1 WHERE pseudo=?', (self.pseudo,))
            self.conn.commit()

    def afficher_imc(self, user, pas):
        self.label_txt_objectif = Label(text="Objectif quotidien:", halign="center",
                                        pos_hint={'center_x': 0.5, 'y': -0.28}, font_size="20sp", color=(0, 0, 0, 1))
        self.ids.home.add_widget(self.label_txt_objectif)

        poids = user[4]
        taille = user[3] / 100  # Convertir la taille en mÃ¨tres
        imc = poids / (taille ** 2)
        self.ids.imc_label.text = f"IMC: {imc:.2f}"
        objectif_pas = self.cursor.execute("SELECT objectif_pas FROM steps WHERE user_id =?", (user[0],)).fetchone()

        if objectif_pas:
            objectif_pas = objectif_pas[0]
            print(objectif_pas)
        if objectif_pas == 0:
            if imc < 18.5:
                pas_obj = 700 - pas - 1
                self.ids.imc_info_label.text = "Vous êtes en insuffisance pondérale."
                self.label_objectif.text = f"Encore {pas_obj} pas !"
            elif 18.5 <= imc < 25:
                pas_obj = 1000 - pas - 1
                self.ids.imc_info_label.text = "Votre poids est normal."
                self.label_objectif.text = f"Encore {pas_obj} pas !"
            elif 25 <= imc < 30:
                pas_obj = 900 - pas - 1
                self.ids.imc_info_label.text = "Vous êtes en surpoids."
                self.label_objectif.text = f"Encore {pas_obj} pas !"
            elif 30 <= imc < 35:
                pas_obj = 750 - pas - 1
                pas_obj = 750 - pas - 1
                self.ids.imc_info_label.text = "Vous êtes obèse."
                self.label_objectif.text = f"Encore {pas_obj} pas !"
            elif 35 <= imc:
                pas_obj = 650 - pas - 1
                self.ids.imc_info_label.text = "Vous êtes en obésité morbide."
                self.label_objectif.text = f"Encore {pas_obj} pas !"
            if pas_obj < 1:
                self.label_objectif.text = "Terminé !"
        else:
            pas_obj = objectif_pas-1
            self.label_objectif.text = pas_obj


    def get_acceleration(self, dt):

        login_screen = self.manager.get_screen('login')
        self.pseudo = login_screen.pseudo_input.text
        user = login_screen.db.get_user_by_pseudo(login_screen.pseudo_input.text)
        if user:
            ami = self.cursor.execute("SELECT pseudo_ami, pas_ami FROM amis WHERE user_id=? ORDER BY id DESC LIMIT 1",
                                      (user[0],)).fetchall()
        debug_ami = self.cursor.execute("SELECT debug FROM users WHERE pseudo=?", (self.pseudo,)).fetchone()
        if debug_ami:
            debug_ami = debug_ami[0]

        if debug_ami == 1 and ami:
            ami = ami[0]
            pseudo_ami = ami[0]
            pas_ami = ami[1]
            label = Label(text=f"Aujourd'hui, {pseudo_ami} a fait {pas_ami} pas", color=(0, 0, 0, 1), font_size=25)
            self.ids.box.add_widget(label)
            #   ami=self.cursor.execute("SELECT pseudo_ami,pas_ami FROM amis WHERE user_id")
            self.cursor.execute('UPDATE users SET debug=0 WHERE pseudo=?', (self.pseudo,))
            self.conn.commit()
        elif debug_ami == 2 and ami:
            tout_ami = self.cursor.execute("SELECT pseudo_ami, pas_ami FROM amis WHERE user_id=?",
                                           (user[0],)).fetchall()
            for i in tout_ami:
                if i[0] == self.pseudo:
                    pass
                else:
                    label = Label(text=f"Aujourd'hui, {i[0]} a fait {i[1]} pas", color=(0, 0, 0, 1), font_size="15sp",
                                  height=20)
                    self.ids.box.add_widget(label)
            self.cursor.execute('UPDATE users SET debug=0 WHERE pseudo=?', (self.pseudo,))
            self.conn.commit()
        self.ids.pseudo.text = self.pseudo
        self.ids.pseudo.color = 1, 1, 1, 1
        self.label_bienvenue = Label(text=f"Bienvenue sur\n Step Pilot !", halign="center",
                                     pos_hint={'center_y': 0.8}, font_size="40sp", color=(0, 0, 0, 1), bold=True)
        self.ids.home.add_widget(self.label_bienvenue)

        global nbr_pas
        val = accelerometer.acceleration[:3]

        if not val == (None, None, None):
            acceleration_x, acceleration_y, acceleration_z = float(val[0]), float(val[1]), float(val[2])
            norme = calculer_norme(acceleration_x, acceleration_y, acceleration_z)

            if detecter_pas(acceleration_x, acceleration_y, acceleration_z, self.derniere_norme,
                            self.seuil_adaptable) or self.debug_2 == True:
                self.debug_2 = False
                user = login_screen.db.get_user_by_pseudo(login_screen.pseudo_input.text)

                current_date = datetime.datetime.now().strftime("%Y-%m-%d")
                co_jour = self.cursor.execute('SELECT connexion FROM steps WHERE user_id=? AND date=?',
                                              (user[0], current_date)).fetchone()

                if user:
                    user_id = user[0]
                    self.somme_pas = self.cursor.execute("SELECT SUM(steps) FROM steps WHERE user_id=?",
                                                         (user_id,)).fetchone()
                    if self.somme_pas[0]:
                        self.somme_pas = self.somme_pas[0] + 1
                        self.ids.pas_tot.text = f"Pas totaux depuis la première connexion: {self.somme_pas}"
                    self.afficher_imc(user, self.nbr_pas)

                    last_reset_date = self.cursor.execute('SELECT MAX(date) FROM steps WHERE user_id=? AND date < ?',
                                                          (user_id, current_date)).fetchone()
                    if last_reset_date:
                        last_reset_date = last_reset_date[0]
                        self.pas_hier = self.cursor.execute('SELECT steps FROM steps WHERE user_id=? AND date=?',
                                                            (user_id, last_reset_date)).fetchone()
                    login_screen.db.record_steps(user_id, self.nbr_pas + 1)
                    if last_reset_date is not None and co_jour is None and self.debug:
                        last_reset_date = last_reset_date[0]
                        if last_reset_date != current_date and last_reset_date is not None:
                            self.pas_hier = self.pas_hier[0] + 1
                            self.db.reset_steps_daily(user_id)
                            self.nbr_pas = 0
                            self.afficher_imc(user, self.nbr_pas)

                            self.label_der_pas.text = f"Nombre de pas le {last_reset_date}: {self.pas_hier}"
                            self.debug = False

                    if co_jour and self.pas_hier:
                        self.pas_hier = self.cursor.execute('SELECT steps FROM steps WHERE user_id=? AND date=?',
                                                            (user_id, last_reset_date)).fetchone()
                        self.pas_hier = self.pas_hier[0] + 1
                        self.label_der_pas.text = f"Nombre de pas le {last_reset_date}: {self.pas_hier}"

                self.nbr_pas += 1
                self.label_pas.text = str(self.nbr_pas)
                nbr_pas = str(self.nbr_pas)
                self.pas_valide = difference
                self.pas_valide = 1.6 - (1.6 / (self.pas_valide + 1))
                self.somme += self.pas_valide * self.seuil_adaptable

            self.derniere_norme = norme


hauteur_ecran = Window.system_size[0]
largeur_ecran = Window.system_size[1]


class MyApp(MDApp):

    # TEMPORAIRE
    def set_daily_goal(self, objectif_input):
        self.conn = sqlite3.connect("base_de_donnees.db")
        self.cursor = self.conn.cursor()

        self.cursor.execute("UPDATE steps SET objectif_pas =?", (objectif_input,))
        self.conn.commit()

    def on_start(self):
        global hauteur_ecran, largeur_ecran
        hauteur_ecran = 600
        largeur_ecran = 300
        if platform == "win":
            Window.size = largeur_ecran, hauteur_ecran
        else:

            Window.size = Window.system_size
            hauteur_ecran = Window.system_size[0]
            largeur_ecran = Window.system_size[1]  # il faut verifier si largeur et hauteur sont exportes

    def build(self):
        self.title = "Step Pilot"
        self.icon = 'logo.png'
        self.loupe = 'loupe.png'
        Builder.load_string(KV)
        sm = ScreenManager()
        db = Database()
        self.accelerometer_instance = AccelerometerScreen(db)
        self.conn = sqlite3.connect("base_de_donnees.db")
        self.cursor = self.conn.cursor()

        sm.add_widget(LoginScreen(db, name='login'))
        self.login_instance = LoginScreen(db, name='login')

        sm.add_widget(RegisterScreen(db, name='register'))
        sm.add_widget(AccelerometerScreen(db))

        sm.add_widget(SocialScreen(self.accelerometer_instance, db, name='social'))
        self.social_instance = SocialScreen(self.accelerometer_instance, db, name='social')

        sm.add_widget(SettingsScreen(name='settings'))

        sm.add_widget(ScoreScreen(db, name='score'))

        sm.add_widget(ProfileScreen(db, name='profile'))
        self.profile_instance = ProfileScreen(db, name='profile')

        return sm


if __name__ == '__main__':
    MyApp().run()