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  # Not actually used!
from kivy.clock import Clock
import webbrowser

if platform == 'ios':
    import ios
if platform == 'ios':
    from plyer import storagepath  # it's only used on iOS, NOT on Android!

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)
        # The following only tested on Android:
        # Window.bind(on_resize=self.resize_event)  # triggers when on-screen keyboard appears and disappears!
        # Window.bind(on_keyboard=self.keyboard_event)  # triggers randomly!
        # Window.bind(on_keyboard_height=self.keyboard_event)  # Never triggers.

    def ios_safe_area(self, _):
        if platform == 'ios':
            self.safe_area = ios.get_safe_area()
            # iPhone 12 Mini: ios.get_safe_area() =  {'top': 43.0, 'bottom': 29.0, 'right': 0.0, 'left': 0.0}
            print("ios.get_safe_area() = ", self.safe_area)
            self.scale = ios.get_scale()  # = kivy.metrics.dp(1)
            self.no_safe_area = True
            for key in self.safe_area:
                if self.safe_area[key] * self.scale > 15: self.no_safe_area = False
                print(f"{self.safe_area[key] * self.scale=}")
            print("self.no_safe_area = ", self.no_safe_area)
            if self.no_safe_area:
                self.root_content = RootContent()
            else:
                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))  # Only relevant on iOS: size_hint=(None, None)
                # Resize app Window when keyboard appears and disappears NOT working on iOS, because of ios.get_safe_area().
        else:
            self.root_content = RootContent()
        print("RootLayout(RelativeLayout): height=", self.height, "width=", self.width)
        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=}')
"""

"""

Android log output from $ adb logcat | grep -w "python" | grep -Fv "extracting"

12-03 12:35:14.795 32384 32434 I python  : [INFO   ] [Window      ] auto add sdl2 input provider
12-03 12:35:14.798 32384 32434 I python  : [INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
12-03 12:35:14.815 32384 32434 I python  : [INFO   ] [Text        ] Provider: sdl2
12-03 12:35:15.167 32384 32434 I python  : 1. app.directory =  .
12-03 12:35:15.235 32384 32434 I python  : 2. app.user_data_dir =  /data/user/0/org.test.myapp/files
12-03 12:35:15.235 32384 32434 I python  : 4. platform =  android
12-03 12:35:15.236 32384 32434 I python  : [WARNING] [Base        ] Unknown <android> provider
12-03 12:35:15.237 32384 32434 I python  : [INFO   ] [Base        ] Start application main loop
12-03 12:35:15.240 32384 32434 I python  : In _init_: RootContent(BoxLayout): x = 0 y = 0 height = 100 width = 100
12-03 12:35:15.340 32384 32434 I python  : RootLayout(RelativeLayout): height= 1704 width= 1080
12-03 12:35:15.429 32384 32434 I python  : [INFO   ] [GL          ] NPOT texture support is available
12-03 12:35:15.618 32384 32434 I python  : After _init_: RootContent(BoxLayout): x = 0 y = 0 height = 1704 width = 1080

"""


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

        # ScrollView with content
        self.scroll_view = MyScrollView(size_hint=(1, 1))
        self.content_layout = BoxLayout(orientation='vertical', size_hint_y=None)

        # This is probably NOT important?!:
        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()
            self.content_layout.add_widget(text_input)

        self.scroll_view.add_widget(self.content_layout)
        self.add_widget(self.scroll_view)
        Clock.schedule_once(self.after_init)

    def after_init(self, _):
        print("After _init_: RootContent(BoxLayout): x =", self.x, "y =", self.y, "height =", self.height, "width =", self.width)

    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()
