1from fsgs import openretro
2from fsgs.Database import Database
3from fsgs.platform import PlatformHandler
4from fsgs.util.gamenameutil import GameNameUtil
5import fsui
6from ..launcher_config import LauncherConfig
7from ..launcher_settings import LauncherSettings
8
9
10class ConfigurationsBrowser(fsui.VerticalItemView):
11    def __init__(self, parent):
12        fsui.VerticalItemView.__init__(self, parent)
13        self.items = []
14        self.game_icon = fsui.Image("launcher:res/16x16/controller.png")
15        self.config_icon = fsui.Image("launcher:res/fsuae_config_16.png")
16        LauncherSettings.add_listener(self)
17        self.update_search()
18
19        self.manual_download_icon = fsui.Image(
20            "launcher:res/16x16/arrow_down_yellow.png"
21        )
22        self.auto_download_icon = fsui.Image(
23            "launcher:res/16x16/arrow_down_green.png"
24        )
25        self.blank_icon = fsui.Image("launcher:res/16x16/blank.png")
26        self.missing_color = fsui.Color(0xA8, 0xA8, 0xA8)
27        self.unpublished_color = fsui.Color(0xCC, 0x00, 0x00)
28
29        self.platform_icons = {}
30
31    def on_destroy(self):
32        LauncherSettings.remove_listener(self)
33
34    def on_select_item(self, index):
35        if index is None:
36            return
37        # self.load_configuration(self.items[index][str("uuid")])
38        self.load_configuration(self.items[index])
39
40    def on_activate_item(self, index):
41        from ..launcherapp import LauncherApp
42
43        LauncherApp.start_game()
44
45    def on_setting(self, key, _):
46        if key in [
47            "config_search",
48            "game_list_uuid",
49            "database_show_games",
50            "database_show_adult",
51            "database_show_unpublished",
52        ]:
53            # if key == "game_list_uuid":
54            self.update_search()
55            if len(self.items) > 0:
56                self.select_item(None)
57                self.select_item(0)
58            else:
59                # self.select_item(None)
60                if LauncherSettings.get("parent_uuid"):
61                    LauncherSettings.set("parent_uuid", "")
62                    LauncherConfig.load_default_config()
63        elif key == "__config_refresh":
64            self.update_search()
65            self.select_item(None)
66            old_parent_uuid = LauncherSettings.get("parent_uuid")
67            if old_parent_uuid:
68                LauncherSettings.set("parent_uuid", "")
69                LauncherSettings.set("parent_uuid", old_parent_uuid)
70        elif key == "parent_uuid" or key == "config_path":
71            if not (
72                LauncherSettings.get("parent_uuid")
73                or LauncherSettings.get("config_path")
74            ):
75                self.select_item(None)
76
77    def set_items(self, items):
78        self.items = items
79        self.update()
80
81    def get_item_count(self):
82        return len(self.items)
83
84    def get_item_text(self, index):
85        item = self.items[index]
86        name = item[str("name")]
87        platform = item[str("platform")] or ""
88        if "[" in name:
89            name, extra = name.split("[", 1)
90            name = name.strip()
91            extra = " \u00b7 " + extra.strip(" ]")
92        else:
93            extra = ""
94        if fsui.toolkit == "wx":
95            sep = "\n"
96        else:
97            sep = " \u00b7 "
98            name = name.replace("\n", " \u00b7 ")
99        if platform == "Amiga" and not openretro:
100            platform = ""
101        elif platform:
102            platform = sep + PlatformHandler.get_platform_name(platform)
103            # if not extra:
104            #     sep = ""
105            # return "{0}{1}{2}{3}".format(name, sep, extra, "")
106        # else:
107        text = "{0}{1}{2}".format(name, extra, platform) or "Missing Name"
108        return text
109
110        # else:
111        #     return "{0} \u00b7 {1}{2}".format(name, extra, platform)
112
113    def get_item_search_text(self, index):
114        # return self.items[index][3]
115        # FIXME: lower-case search string?
116        return self.items[index][str("sort_key")]
117
118    def get_item_text_color(self, index):
119        have = self.items[index][str("have")]
120        if not have:
121            return self.missing_color
122        published = self.items[index]["published"]
123        if not published:
124            return self.unpublished_color
125
126    def get_item_icon(self, index):
127        item = self.items[index]
128        platform_id = (item[str("platform")] or "").lower()
129        if item[str("have")] == 1:
130            return self.manual_download_icon
131        elif item[str("have")] == 0:
132            return self.blank_icon
133        elif item[str("have")] == 2:
134            return self.auto_download_icon
135        elif item[str("have")] == 4:
136            if platform_id not in self.platform_icons:
137                try:
138                    icon = fsui.Image(
139                        "launcher:res/16x16/{0}.png".format(platform_id)
140                    )
141                except Exception:
142                    icon = self.game_icon
143                self.platform_icons[platform_id] = icon
144            return self.platform_icons[platform_id]
145        else:
146            return self.config_icon
147
148    # def on_get_item_tooltip(self, row, column):
149    #     return self.items[row][1]
150    #     #text = text.replace("\nAmiga \u00b7 ", "\n")
151
152    def update_search(self):
153        search = LauncherSettings.get("config_search").strip().lower()
154        print("search for", search)
155        words = []
156        special = []
157        for word in search.split(" "):
158            word = word.strip()
159            if not word:
160                continue
161            if ":" in word[1:-1]:
162                special.append(word)
163            else:
164                words.append(word)
165        terms = GameNameUtil.extract_search_terms(" ".join(words))
166        terms.update(special)
167
168        database = Database.get_instance()
169
170        try:
171            have = int(LauncherSettings.get("database_show_games"))
172        except ValueError:
173            # default is show all downloadable and locally available games
174            have = 1
175        items = database.find_games_new(
176            " ".join(terms),
177            have=have,
178            list_uuid=LauncherSettings.get("game_list_uuid"),
179        )
180
181        self.set_items(items)
182
183    # noinspection PyMethodMayBeStatic
184    def load_configuration(self, item):
185        if item[str("uuid")]:
186            LauncherSettings.set("parent_uuid", item[str("uuid")])
187        else:
188            config_path = Database.get_instance().decode_path(
189                item[str("path")]
190            )
191            print("load config from", config_path)
192            LauncherConfig.load_file(config_path)
193            LauncherSettings.set("parent_uuid", "")
194