from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.utils import platform
from kivy.core.window import Window
from kivy.clock import Clock
import webbrowser

if platform == 'ios':
    import ios

from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.textinput import TextInput
from kivy.properties import ColorProperty

class ScalableLabel(Label):
    background_color = ColorProperty('black')  # this lets you use color names in kv or python.

class ScalableButton(Button):
    pass

class MyScrollView(ScrollView):
    pass

class FixedTextinput(TextInput):
    pass

Builder.load_string('''
#:set my_font_size sp(15)
#:set large_font_size sp(30)
#:set my_padding dp(10)
#:set my_bar_color [.3, .3, .3, .9]
#:set white 1, 1, 1, 1
#:set black 0, 0, 0, 1

<ScalableButton>:
    text: '(...)'  # Will be set later in Python.
    font_size: my_font_size
    text_size: self.width, None
    size_hint_y: None
    padding: (my_padding, my_padding)
    height: self.texture_size[1]
    background_color: [0, 1, 0, 1]

<ScalableLabel>:
    text: '(...)'  # Will be set later in Python.
    font_size: my_font_size
    text_size: self.width, None
    size_hint_y: None
    padding: (my_padding,my_padding)
    height: self.texture_size[1]
    background_color: [0, 0, 0, 1]
    canvas.before:
        Color:
            rgba: root.background_color
        Rectangle:
            size: self.size
            pos: self.pos

<MyScrollView>:
    do_scroll_x: False
    do_scroll_y: True
    bar_color: my_bar_color
    bar_inactive_color: my_bar_color
    bar_width: 0.6 * my_padding
    canvas.before:
        Color:
            rgba: 0.9, 0.9, 0.9, 1
        Rectangle:
            size: self.size
            pos: self.pos

<FixedTextinput>:
    text: ''
    multiline: False
    size_hint_y: None
    height: self.minimum_height

''')

class ChooseLang(BoxLayout):
    def lang_chosen(self, langs):
        app = App.get_running_app()
        app.root.children[0].lang_choose_done()

class RootLayout(RelativeLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        app = App.get_running_app()
        print("1. app.directory = ", app.directory)
        print("2. app.user_data_dir = ", app.user_data_dir)
        app_dir_readonly = app.directory
        print("4. platform = ", platform)
        if platform == 'ios':
            print("3. storagepath.get_home_dir() = ", storagepath.get_home_dir())
            internal_files_path = storagepath.get_home_dir() + 'Library/'
            print("5. storagepath.get_home_dir()/Library/ = ", internal_files_path)
            shared_files_path = app.user_data_dir
        else:  # == Android for any practical purposes...
            internal_files_path = app.user_data_dir  # Used for 'cur-ref-point'-files and other internal files.
            shared_files_path = app.user_data_dir

        Clock.schedule_once(self.ios_safe_area)
        # Window.bind(on_keyboard=self.keyboard_event)
        # Window.bind(on_resize=self.resize_event)

    def ios_safe_area(self, _):
        if platform == 'ios':
            self.safe_area = ios.get_safe_area()
            print("ios.get_safe_area() = ", self.safe_area)
            self.scale = ios.get_scale()  # = kivy.metrics.dp(1)
        else:
            self.safe_area = {'top': 0.0, 'bottom': 0.0, 'right': 0.0, 'left': 0.0}
            self.scale = 1
        print("RootLayout(RelativeLayout): height=", self.height, "width=", self.width)
        new_x = self.scale * self.safe_area["left"]
        new_y = self.scale * self.safe_area["bottom"]
        new_width = self.width - self.scale * (self.safe_area["left"] + self.safe_area["right"])
        new_height = self.height - self.scale * (self.safe_area["bottom"] + self.safe_area["top"])
        self.root_content = RootContent(x=new_x, y=new_y, width=new_width, height=new_height, size_hint=(None, None))
        self.add_widget(self.root_content)

# NOTE! The following 3 methods are NOT in use!!:

    def keyboard_event(self, window, height, key_height, *args):
        Clock.schedule_once(lambda dt: self.adjust_for_keyboard(key_height), 0)

    def resize_event(self, window, width, height):
        Clock.schedule_once(lambda dt: self.adjust_for_keyboard(0), 0)  # Reset layout on resize

    def adjust_for_keyboard(self, key_height):
        print(f'EMPTY adjust_for_keyboard: {Window.height=} {key_height=}')

"""
Originally...:
    def adjust_for_keyboard(self, key_height):

        if key_height > 200:  # This threshold might need adjustment based on testing.
            print(f'key_height > 200: {Window.height=} {key_height=}')
            # Keyboard is visible, adjust the height
            self.root_content.size_hint_y = None
            self.root_content.height = Window.height - key_height
        else:
            print(f'200 > key_height: {Window.height=} {key_height=}')
            # Keyboard is hidden, reset to use full window height
            self.root_content.size_hint_y = 1
            self.root_content.height = Window.height
"""

class RootContent(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        print("RootContent(BoxLayout): x =", self.x, "y =", self.y, "height =", self.height, "width =", self.width)

        self.size_hint_y = 1
        self.height = Window.height

        # ScrollView with content
        self.scroll_view = MyScrollView(size_hint=(1, 1))
        self.content_layout = BoxLayout(orientation='vertical', size_hint_y=None)
        self.content_layout.bind(minimum_height=self.content_layout.setter('height'))
        new_target_prompt = ScalableLabel(text="sdgfh sdfh dsfgh dsfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg "
                                               "sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg "
                                               "sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg "
                                               "sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg sdfg")
        self.content_layout.add_widget(new_target_prompt)

        # Add TextInputs to the layout
        for i in range(6):
            label = ScalableLabel(text=f"Label {i+1}..:")
            self.content_layout.add_widget(label)
            text_input = FixedTextinput(size_hint_y=None, height=50, multiline=False)
            self.content_layout.add_widget(text_input)

        self.scroll_view.add_widget(self.content_layout)
        self.add_widget(self.scroll_view)

    def lang_choose_done(self):
        pass  # Placeholder for actual implementation

    def send_KML_done(self):
        pass  # Placeholder for actual implementation

class GeoESPTraining(App):
    def build(self):
        return RootLayout()

    def action_ref(self, args):
        print("args = ", args)
        webbrowser.open(args[1])

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