import os
import time
from Options import options
from MonstersReference import monsters_ref
from i18n import i18n_fr
import re

VIEW_OVERVIEW = -8
VIEW_COMBAT = -4
VIEW_FM = -5
VIEW_HUNT = -6
VIEW_SEARCH = -7
ADVANCED = -1
DUMP = -2
OPTIONS = -3

class Gui:
    def __init__(self):
        self.display = VIEW_COMBAT
        with open(f'{os.path.dirname(__file__)}/web/base.html', 'r', encoding='utf8') as f:
            self.base_html = f.read()
        with open(f'{os.path.dirname(__file__)}/web/combat.html', 'r', encoding='utf8') as f:
            self.combat_ref_html = f.read()
        self.combat_html = ""
        with open(f'{os.path.dirname(__file__)}/web/combat_player.html', 'r', encoding='utf8') as f:
            self.combat_player_ref_html = f.read()
        self.combat_player_html = {}
        with open(f'{os.path.dirname(__file__)}/web/header.html', 'r', encoding='utf8') as f:
            self.header_html_ref = f.read()
        self.dump_html = ""
        self.combat_html = ""
        with open(f'{os.path.dirname(__file__)}/web/fm.html', 'r', encoding='utf8') as f:
            self.ref_fm_html = f.read()
        self.item_fm_html = ""
        self.rune_fm_html = ""
        self.pool_fm_html = 0
        self.text_fm_html = ""
        self.update_fm_html()
        self.hunt_html = ""
        self.modal_html = "-1"
        self.advanced_html = ""
        with open(f'{os.path.dirname(__file__)}/web/popup.html', 'r', encoding='utf8') as f:
            self.popup_html_ref = f.read()
        self.popup_html = ""
        with open(f'{os.path.dirname(__file__)}/web/popup_names.html', 'r', encoding='utf8') as f:
            self.popup_html_names = f.read()
        with open(f'{os.path.dirname(__file__)}/web/overview.html', 'r', encoding='utf8') as f:
            self.ref_overview_html = f.read()
        self.overview_html = ""
        self.window = None
        self.update_header()
        self.update_popup(None)

    def update_fm_html(self):
        self.fm_html = self.ref_fm_html.replace("__ITEM_NAME__", self.item_fm_html).replace("__RUNE_NAME__", self.rune_fm_html).replace("__POOL_VALUE__", str(self.pool_fm_html)).replace("__TEXT_FM_INFOS__", self.text_fm_html)
        if self.display == VIEW_FM:
            self.send_body()

    def update_combat_html(self, value):
        self.combat_html = self.combat_ref_html.replace("__COMBAT_REPLACE__", value)
        if self.display == VIEW_COMBAT:
            self.send_body()

    def update_overview_html(self, name, pa, pm, base_info, effects):
        self.overview_html = self.ref_overview_html.replace("__PLAYER_NAME__", name).replace("__PLAYER_PA__", pa).replace("__PLAYER_PM__", pm).replace("__GENERIC_INFOS_PLAYER__", base_info)
        effect_string = ""
        for e in effects:
            val = "PA" if e.effect_type == 1 else "PM" if e.effect_type == 23 else e.effect_type
            delay = f"in {e.delay} turns" if e.delay > 0 else ""
            turns = f"(infinite)" if e.turn_duration == -1000 else f"{e.turn_duration} turns" if e.delay <= 0 else ""
            effect_string += f"{e.name} {e.operator}{e.delta} {val} {delay}{turns}"
            effect_string += "<br />"
        self.overview_html = self.overview_html.replace("__PLAYER_BUFF_DISPLAY__", effect_string)
        if self.display == VIEW_OVERVIEW:
            self.send_body()

    def update_player_combat_html(self, player, string):
        self.combat_player_html[player] = self.combat_player_ref_html.replace("__COMBAT_PLAYER_REPLACE__", string)
        if self.display == player:
            self.send_body()

    def set_window(self, window):
        self.window = window

    def set_view_combat(self):
        self.display = VIEW_COMBAT
        self.send_body()

    def set_view_combat_player(self, player_name):
        self.display = player_name
        self.send_body()

    def set_view_overview(self):
        self.display = VIEW_OVERVIEW
        self.send_body()

    def set_view_fm(self):
        self.display = VIEW_FM
        self.send_body()

    def set_view_hunt(self):
        self.display = VIEW_HUNT
        self.send_body()

    def set_combat_player_view(self, view_name):
        self.display = view_name

    def update_settings_player(self, username):
        options.update_settings(username, multi=False)

    def update_settings_multi(self, multi=True):
        options.update_settings(options.username, multi=True)

    def send_body(self):
        if self.window is not None:
            self.window.evaluate_js(r"update_main()")

    def send_header(self):
        if self.window is not None:
            self.window.evaluate_js(r"update_header()")

    def get_body(self):
        if self.display == VIEW_COMBAT:
            return self.combat_html
        elif self.display == VIEW_FM:
            return self.fm_html
        elif self.display == VIEW_HUNT:
            return self.hunt_html
        elif self.display == VIEW_OVERVIEW:
            return self.overview_html
        elif self.display in self.combat_player_html.keys():
            return self.combat_player_html[self.display]

    def get_header(self):
        self.update_header()
        return self.header_html

    def update_fm_pool(self, value):
        options.relicat = float(value)

    def update_header(self):
        checked = "checked" if options.multi == True else ""
        self.header_html = self.header_html_ref.replace("__USERNAME__", str(options.username if options.multi == False else "Multi"))
        select = ""
        self.header_html = self.popup_html + self.header_html

    def update_username(self, uname):
        if self.window is not None:
            self.window.evaluate_js(r'update_username("{}")').format(uname)

    def update_popup(self, type):
        html = ''
        if type == 'name':
            select = ''
            if options.multi == True:
                val = 'checked="checked"'
            select = f"""
    <input type="checkbox" name="rGroup" value="all" {val}/>
    <label class="whatever all_char" for="all" onclick="select_all_users()">All</label>
            """
            if len(options.available_windows) > 0:
                for k, i in options.available_windows.items():
                    val = ''
                    if i['name'] == options.username or options.multi == True:
                        val = 'checked="checked"'
                    select += f"""
    <input type="checkbox" name="rGroup" value="{i['name']}" id="{i['name']}" {val} />
    <label class="whatever" for="{i['name']}" onclick="select_user('{i['name']}')">{i['name']}</label>
                """
            html = self.popup_html_names.replace("__ALL_NAMES__", select)
            return html
        self.popup_html = self.popup_html_ref.replace("__POPUP_CONTENT__", html)
        self.header_html = self.popup_html + self.header_html
        return self.popup_html

    def log(self, string):
        print (string)

    def initial_values(self):
        return
        with open(f'{os.path.dirname(__file__)}/web/base_edge.html') as f:
            html = f.read()
        with open(f'{os.path.dirname(__file__)}/web/script.js') as f:
            html = html.replace("__SCRIPT_REPLACE__", f.read())
        with open(f'{os.path.dirname(__file__)}/web/webview.css') as f:
            html = html.replace("__STYLE_REPLACE__", f.read())
        html = html.replace("__FONT_URL__", f'{os.path.dirname(__file__)}/web')

    def on_pywebview_ready(self):
        self.send_header()
        self.send_body()

    def exit_window(self):
        self.window.destroy()

    def minimize_window(self):
        self.window.minimize()

GUI = Gui()