import sys
import platform
import sqlite3
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem
from kivy.uix.popup import Popup
from kivy.uix.colorpicker import ColorPicker
from kivy.properties import BooleanProperty
from plyer import notification
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64

# AES Encryption setup
key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_GCM)
nonce = cipher.nonce

def encrypt_message(message):
    ciphertext, tag = cipher.encrypt_and_digest(message.encode())
    return base64.b64encode(nonce + tag + ciphertext).decode()

def decrypt_message(encrypted_message):
    encrypted_message = base64.b64decode(encrypted_message)
    nonce = encrypted_message[:16]
    tag = encrypted_message[16:32]
    ciphertext = encrypted_message[32:]
    cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
    return cipher.decrypt_and_verify(ciphertext, tag).decode()

def save_message(address, message, direction):
    with sqlite3.connect('messages.db') as conn:
        c = conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS messages
                     (address TEXT, message TEXT, direction TEXT,
                      timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')
        c.execute("INSERT INTO messages (address, message, direction) VALUES (?, ?, ?)",
                  (address, message.replace("'", "''"), direction))
        conn.commit()

def show_notification(message):
    notification.notify(title='Bluetooth Messenger', message=message, timeout=5)

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout):
    pass

class SelectableButton(RecycleDataViewBehavior, Button):
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)

    def refresh_view_attrs(self, rv, index, data):
        self.index = index
        return super(SelectableButton, self).refresh_view_attrs(rv, index, data)

    def on_touch_down(self, touch):
        if super(SelectableButton, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        self.selected = is_selected
        if is_selected:
            print("selection changed to {0}".format(rv.data[index]))
        else:
            print("selection removed for {0}".format(rv.data[index]))

class RV(RecycleView):
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = [{'text': str(i)} for i in range(20)]

class BluetoothMessengerApp(App):
    def build(self):
        self.current_theme_color = (1, 1, 1, 1)
        self.tab_panel = TabbedPanel()

        # Chat tab
        self.chat_tab = TabbedPanelItem(text='Chat')
        self.chat_layout = BoxLayout(orientation='vertical')

        self.device_label = Label(text='Выберите устройство:')
        self.device_combo = RV()
        self.message_label = Label(text='Сообщение:')
        self.message_input = TextInput()
        self.send_button = Button(text='Отправить')
        self.send_button.bind(on_press=self.send_message)
        self.output_text = TextInput(readonly=True)

        self.chat_layout.add_widget(self.device_label)
        self.chat_layout.add_widget(self.device_combo)
        self.chat_layout.add_widget(self.message_label)
        self.chat_layout.add_widget(self.message_input)
        self.chat_layout.add_widget(self.send_button)
        self.chat_layout.add_widget(self.output_text)

        self.chat_tab.add_widget(self.chat_layout)
        self.tab_panel.add_widget(self.chat_tab)

        # Settings tab
        self.settings_tab = TabbedPanelItem(text='Settings')
        self.settings_layout = BoxLayout(orientation='vertical')

        self.theme_button = Button(text='Выбрать цвет темы')
        self.theme_button.bind(on_press=self.change_theme_color)
        self.settings_layout.add_widget(self.theme_button)

        self.settings_tab.add_widget(self.settings_layout)
        self.tab_panel.add_widget(self.settings_tab)

        return self.tab_panel

    def change_theme_color(self, instance):
        color_picker = ColorPicker()
        popup = Popup(title='Выберите цвет темы', content=color_picker, size_hint=(0.9, 0.9))
        color_picker.bind(color=self.update_theme)
        popup.open()

    def update_theme(self, instance, value):
        self.current_theme_color = value
        self.tab_panel.background_color = self.current_theme_color

    def send_message(self, instance):
        address = self.device_combo.data[0]['text'] if self.device_combo.data else None
        message = self.message_input.text
        if address and message:
            encrypted_message = encrypt_message(message)
            # Здесь нужно добавить код для отправки сообщения через Bluetooth
            save_message(address, message, "sent")
            show_notification(f"Сообщение отправлено на {address}")
            self.output_text.text += f"Сообщение отправлено на {address}\n"
        else:
            show_notification("Пожалуйста, выберите устройство и введите сообщение.")

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



ДОБАВЬ и ИЗМЕНИ!!!
дата сообщения, все функции тг
улучшить безопасность
доступ к уведомлениям телефона
кнопка для полного удаления приложения и всех переписок



некоторые меню сломались, а так же мне не нравится дизайн

как мне это перенести на ANDOROID, если некоторые библиотеки не работают на нем?? ВЫБЕРИ БИБЛИОТЕКИ КОТОРЫЕ 100%  СОВМЕСТИМЫ С ANDOROID