import API
import time

import SL_Combat_Settings as S
import SL_Combat_Rater as R

# =============================================================================
# SL_Combat_Gump.py  -  Shattered Legacy combat script: the windows
# A module of SL_Combat.py (run that one).
#
# The control gump (status, on/off, mode, pause, panic, the loot helper
# toggles, profile, buttons to the other windows), the Settings window, the
# Results window (rated items) and the Profile editor with Suggest. Every
# control comes from API.Gumps; button callbacks run inside
# API.ProcessCallbacks, which the entry script calls every tick.
# =============================================================================

BG = "#141414"
TEXT = "#E8E8E8"
DIM = "#9A9A9A"
FONT_SIZE = 15

NUMBER_SETTINGS = [
    # key, label, float?
    ("engageRange", "Engage range", False), ("seekRange", "AFK seek range", False), ("leashRange", "AFK leash", False),
    ("bandageAt", "Bandage under %", False), ("bandageDelayOverride", "Bandage secs (0 auto)", False),
    ("healPotionAt", "Heal potion under %", False), ("curePotionAt", "Cure potion under %", False),
    ("refreshAt", "Refresh under % stam", False), ("potionCooldown", "Potion cooldown s", False),
    ("companionHealAt", "Companion heal under %", False), ("guardAt", "All guard me under %", False),
    ("panicAt", "Auto panic under % (0 off)", False), ("specialMana", "Special needs mana", False),
    ("specialCooldown", "Special cooldown s", True), ("recoverHp", "AFK recover to % hp", False),
    ("recoverStam", "AFK recover to % stam", False), ("keepAt", "Keep at score", True),
    ("upgradeMargin", "Upgrade margin", True),
]
SPECIALS = ["primary", "secondary", "alternate", "none"]
PANIC_ACTIONS = ["heal", "recall", "run"]
RECALL_SPELLS = ["Recall", "Sacred Journey"]
SUGGEST_SKILLS = list(R.COMBAT_SKILLS) + list(R.CASTER_SKILLS) + ["Healing", "Anatomy", "Lumberjacking", "Mining", "Tactics"]


class UI:
    def __init__(self, core, on_hotkeys_changed=None):
        self.core = core
        self.on_hotkeys_changed = on_hotkeys_changed
        self.main = None
        self.settings = None
        self.results = None
        self.profile = None
        self.lbl_status = None
        self.lbl_mode = None
        self.lbl_rank = None
        self.lbl_last = None
        self.cb_loot = None
        self.cb_compare = None
        self.cb_sort = None
        self.btn_onoff = None
        self.btn_mode = None
        self.btn_pause = None
        self.results_key = None
        self.profile_boxes = {}
        self.profile_name_box = None
        self.profile_notes = None
        self.suggested = None
        self.settings_boxes = {}
        self.pick_nearest = None
        self.pick_lowest = None
        self.dd_special = None
        self.dd_panic = None
        self.dd_recall = None
        self.hunt_box = None
        self.hotkey_boxes = {}
        self.last_refresh = 0.0

    # -- building blocks ---------------------------------------------------------------

    def _gump(self, w, h, title, x=120, y=120):
        g = API.Gumps.CreateGump(True, True)
        g.SetRect(x, y, w, h)
        bg = API.Gumps.CreateGumpColorBox(0.88, BG)
        bg.SetRect(0, 0, w, h)
        g.Add(bg)
        self._label(g, title, 10, 6, w - 20, 20, "#FFD966", 17)
        return g

    def _label(self, g, text, x, y, w, h=18, color=TEXT, size=FONT_SIZE):
        lb = API.Gumps.CreateGumpTTFLabel(str(text), size, color)
        lb.SetRect(x, y, w, h)
        g.Add(lb)
        return lb

    def _button(self, g, text, x, y, w, h, fn):
        b = API.Gumps.CreateSimpleButton(str(text), w, h)
        b.SetPos(x, y)
        g.Add(b)
        API.Gumps.AddControlOnClick(b, fn)
        return b

    def _check(self, g, text, x, y, checked):
        cb = API.Gumps.CreateGumpCheckbox(str(text), 0, bool(checked))
        cb.SetPos(x, y)
        g.Add(cb)
        return cb

    def _textbox(self, g, text, x, y, w, h=22, multiline=False):
        tb = API.Gumps.CreateGumpTextBox(str(text), w, h, multiline, 15)
        tb.SetPos(x, y)
        g.Add(tb)
        return tb

    def _dropdown(self, g, items, selected, x, y, w, fn=None):
        dd = API.Gumps.CreateDropDown(w, list(items), max(0, selected))
        dd.SetPos(x, y)
        g.Add(dd)
        if fn is not None:
            dd.OnDropDownOptionSelected(fn)
        return dd

    def _show(self, g):
        API.Gumps.AddGump(g)
        return g

    def _alive(self, g):
        return g is not None and not g.IsDisposed

    def _close(self, g):
        if self._alive(g):
            try:
                g.Dispose()
            except Exception:
                pass

    # -- main window ---------------------------------------------------------------------

    def open_main(self):
        self._close(self.main)
        s = S.SETTINGS
        w, h = 320, 332
        g = self._gump(w, h, "SL_Combat", 60, 160)
        try:
            g.CanCloseWithRightClick = False
        except Exception:
            pass
        self.lbl_status = self._label(g, "", 10, 30, w - 20)
        self.lbl_mode = self._label(g, "", 10, 48, w - 20, 18, DIM)
        self.btn_onoff = self._button(g, "On", 10, 70, 60, 22, lambda: self.core.toggle())
        self.btn_mode = self._button(g, "Assist", 76, 70, 70, 22, lambda: self.core.toggle_mode())
        self.btn_pause = self._button(g, "Pause", 152, 70, 60, 22, lambda: self.core.toggle_pause())
        self._button(g, "PANIC", 218, 70, 60, 22, lambda: self.core.panic())
        self.cb_loot = self._check(g, "Loot helper", 10, 100, s.get("lootHelper"))
        self.cb_compare = self._check(g, "Compare", 118, 100, s.get("compareMode"))
        self.cb_sort = self._check(g, "Auto-sort", 210, 100, s.get("autoSort"))
        self._label(g, "Profile", 10, 128, 60)
        names = sorted(s["profiles"].keys())
        idx = names.index(s["activeProfile"]) if s["activeProfile"] in names else 0
        self._dropdown(g, names, idx, 70, 126, 170, lambda i: self._pick_profile(names, i))
        self._button(g, "Rate backpack", 10, 156, 100, 22, lambda: (self.core.rate_backpack(), self.open_results()))
        self._button(g, "Results", 116, 156, 60, 22, lambda: self.open_results())
        self._button(g, "Profile", 182, 156, 60, 22, lambda: self.open_profile())
        self._button(g, "Suggest", 248, 156, 60, 22, lambda: self.open_profile(suggest=True))
        self._button(g, "Settings", 10, 184, 70, 22, lambda: self.open_settings())
        self._button(g, "Set anchor", 86, 184, 80, 22, lambda: self.core.set_anchor_here())
        self._button(g, "Add companion", 172, 184, 110, 22, lambda: self.core.add_companion())
        self._button(g, "Refresh rank", 10, 212, 90, 22, lambda: self.core.refresh_rank())
        self.lbl_rank = self._label(g, "", 106, 214, w - 116, 18, DIM, 13)
        self.lbl_last = self._label(g, "", 10, 240, w - 20, 54, DIM, 13)
        hk = s.get("hotkeys", {})
        self._label(g, "Keys: %s on/off, %s mode, %s pause, %s panic" % (
            hk.get("toggle"), hk.get("mode"), hk.get("pause"), hk.get("panic")), 10, 300, w - 20, 30, DIM, 12)
        self.main = self._show(g)
        self.refresh(force=True)

    def _pick_profile(self, names, index):
        if 0 <= index < len(names):
            S.set("activeProfile", names[index])
            API.SysMsg("[SL_Combat] profile: %s" % names[index], 68)

    def refresh(self, force=False):
        now = time.time()
        if not force and now - self.last_refresh < 0.5:
            return
        self.last_refresh = now
        if not self._alive(self.main):
            return
        core = self.core
        s = S.SETTINGS
        try:
            self.lbl_status.SetText("%s: %s" % (("ON" if core.enabled() else "OFF"), core.status))
            self.lbl_mode.SetText("Mode %s, state %s, target %s" % (s.get("mode"), core.state, core.target_name or "none"))
            self.btn_onoff.SetText("Off" if core.enabled() else "On")
            self.btn_mode.SetText("AFK" if s.get("mode") == "afk" else "Assist")
            self.btn_pause.SetText("Resume" if core.paused else "Pause")
            self.lbl_rank.SetText(core.rank_text())
            if core.rated:
                r = core.rated[0]
                extra = "" if r.get("delta") is None else " (%+.1f)" % r["delta"]
                self.lbl_last.SetText("Last: %s %s %.1f%s. %s" % (r["name"], r["tier"], r["score"], extra, r["reason"]))
            else:
                self.lbl_last.SetText("Last rated: nothing yet")
            for cb, key in ((self.cb_loot, "lootHelper"), (self.cb_compare, "compareMode"), (self.cb_sort, "autoSort")):
                v = bool(cb.IsChecked)
                if v != bool(s.get(key)):
                    S.set(key, v)
        except Exception:
            pass
        if self._alive(self.results):
            key = (len(core.rated), core.rated[0]["serial"] if core.rated else 0,
                   core.rated[0].get("sorted") if core.rated else "")
            if key != self.results_key:
                self.open_results()

    # -- settings window ---------------------------------------------------------------

    def open_settings(self):
        self._close(self.settings)
        s = S.SETTINGS
        w, h = 470, 500
        g = self._gump(w, h, "SL_Combat settings", 400, 120)
        self.settings_boxes = {}
        half = (len(NUMBER_SETTINGS) + 1) // 2
        for i, (key, label, is_float) in enumerate(NUMBER_SETTINGS):
            col = 0 if i < half else 1
            row = i if i < half else i - half
            x = 10 + col * 230
            y = 32 + row * 26
            self._label(g, label, x, y + 2, 165, 18, TEXT, 13)
            self.settings_boxes[key] = self._textbox(g, s.get(key), x + 168, y, 52)
        y = 32 + half * 26 + 6
        self._label(g, "When attacked, pick", 10, y + 2, 130, 18, TEXT, 13)
        self.pick_nearest = API.Gumps.CreateGumpRadioButton("nearest", 7, 0x00D0, 0x00D1, 0xFFFF, s.get("pickBy") != "lowesthp")
        self.pick_nearest.SetPos(140, y)
        g.Add(self.pick_nearest)
        self.pick_lowest = API.Gumps.CreateGumpRadioButton("lowest HP", 7, 0x00D0, 0x00D1, 0xFFFF, s.get("pickBy") == "lowesthp")
        self.pick_lowest.SetPos(230, y)
        g.Add(self.pick_lowest)
        y += 28
        self._label(g, "Special", 10, y + 2, 60, 18, TEXT, 13)
        self.dd_special = self._dropdown(g, SPECIALS, SPECIALS.index(s.get("special")) if s.get("special") in SPECIALS else 0, 60, y, 90)
        self._label(g, "Panic", 160, y + 2, 50, 18, TEXT, 13)
        self.dd_panic = self._dropdown(g, PANIC_ACTIONS, PANIC_ACTIONS.index(s.get("panicAction")) if s.get("panicAction") in PANIC_ACTIONS else 0, 200, y, 70)
        self._label(g, "Spell", 280, y + 2, 40, 18, TEXT, 13)
        self.dd_recall = self._dropdown(g, RECALL_SPELLS, RECALL_SPELLS.index(s.get("recallSpell")) if s.get("recallSpell") in RECALL_SPELLS else 0, 320, y, 130)
        y += 30
        self.hotkey_boxes = {}
        hk = s.get("hotkeys", {})
        for i, (key, label) in enumerate((("toggle", "On/off key"), ("mode", "Mode key"), ("pause", "Pause key"), ("panic", "Panic key"))):
            x = 10 + (i % 2) * 230
            yy = y + (i // 2) * 26
            self._label(g, label, x, yy + 2, 80, 18, TEXT, 13)
            self.hotkey_boxes[key] = self._textbox(g, hk.get(key, ""), x + 85, yy, 135)
        y += 56
        self._label(g, "Hunt list (gray names, separated by ;)", 10, y, 300, 18, TEXT, 13)
        y += 20
        self.hunt_box = self._textbox(g, "; ".join(s.get("huntList", []) or []), 10, y, w - 20)
        y += 30
        self._button(g, "Keep bag", 10, y, 70, 22, lambda: self._set_bag("Keep"))
        self._button(g, "Unravel bag", 86, y, 85, 22, lambda: self._set_bag("Unravel"))
        self._button(g, "Sell bag", 177, y, 70, 22, lambda: self._set_bag("Sell"))
        self._button(g, "Recall rune", 253, y, 85, 22, lambda: self._set_rune())
        self._button(g, "Clear companions", 344, y, 116, 22, lambda: self.core.clear_companions())
        y += 30
        self._button(g, "Save", 10, y, 80, 24, lambda: self._save_settings())
        self._button(g, "Close", 96, y, 80, 24, lambda: self._close(self.settings))
        self._label(g, "Bags: Keep %s, Unravel %s, Sell %s; rune %s" % (
            self._bag_text("Keep"), self._bag_text("Unravel"), self._bag_text("Sell"),
            hex(int(s.get("recallRune", 0) or 0)) if s.get("recallRune") else "none"), 186, y + 4, 280, 18, DIM, 12)
        self.settings = self._show(g)

    def _bag_text(self, key):
        v = int((S.SETTINGS.get("bags", {}) or {}).get(key, 0) or 0)
        return hex(v) if v else "none"

    def _set_bag(self, key):
        API.SysMsg("[SL_Combat] target the %s bag" % key, 68)
        serial = API.RequestTarget(10)
        if serial:
            bags = dict(S.SETTINGS.get("bags", {}) or {})
            bags[key] = int(serial)
            S.set("bags", bags)
            API.SysMsg("[SL_Combat] %s bag set" % key, 68)
            self.open_settings()

    def _set_rune(self):
        API.SysMsg("[SL_Combat] target the rune (or runebook) to recall to in a panic", 68)
        serial = API.RequestTarget(10)
        if serial:
            S.set("recallRune", int(serial))
            API.SysMsg("[SL_Combat] recall rune set", 68)
            self.open_settings()

    def _save_settings(self):
        s = S.SETTINGS
        for key, label, is_float in NUMBER_SETTINGS:
            tb = self.settings_boxes.get(key)
            if tb is None:
                continue
            s[key] = S.to_float(tb.Text, s.get(key)) if is_float else S.to_int(tb.Text, s.get(key))
        try:
            s["pickBy"] = "lowesthp" if self.pick_lowest.IsChecked else "nearest"
        except Exception:
            pass
        try:
            s["special"] = SPECIALS[self.dd_special.GetSelectedIndex()]
            s["panicAction"] = PANIC_ACTIONS[self.dd_panic.GetSelectedIndex()]
            s["recallSpell"] = RECALL_SPELLS[self.dd_recall.GetSelectedIndex()]
        except Exception:
            pass
        old_keys = dict(s.get("hotkeys", {}))
        new_keys = {}
        for key, tb in self.hotkey_boxes.items():
            new_keys[key] = (tb.Text or "").strip().upper() or old_keys.get(key, "")
        s["hotkeys"] = new_keys
        s["huntList"] = [x.strip() for x in (self.hunt_box.Text or "").split(";") if x.strip()]
        S.save()
        if new_keys != old_keys and self.on_hotkeys_changed is not None:
            self.on_hotkeys_changed(old_keys, new_keys)
        API.SysMsg("[SL_Combat] settings saved", 68)
        self.open_main()

    # -- results window ----------------------------------------------------------------

    def open_results(self):
        self._close(self.results)
        core = self.core
        w, h = 560, 430
        g = self._gump(w, h, "Rated items (newest first)", 400, 80)
        sa = API.Gumps.CreateGumpScrollArea(0, 30, w, h - 70)
        g.Add(sa)
        if not core.rated:
            lb = API.Gumps.CreateGumpTTFLabel("Nothing rated yet: kill something, or Rate backpack.", 14, DIM)
            lb.SetRect(10, 6, w - 30, 18)
            sa.Add(lb)
        for i, r in enumerate(core.rated):
            y = i * 40
            try:
                pic = API.Gumps.CreateGumpItemPic(int(r.get("graphic", 0)), 36, 36)
                pic.SetPos(6, y)
                try:
                    pic.SetEntityTooltip(int(r["serial"]))
                except Exception:
                    pass
                sa.Add(pic)
            except Exception:
                pass
            color = R.TIER_COLORS.get(r["tier"], TEXT)
            head = "%s   %s %.1f" % (r["name"], r["tier"], r["score"])
            if r.get("delta") is not None:
                head += "  (%+.1f vs %s)" % (r["delta"], r.get("slot") or "equipped")
            lb = API.Gumps.CreateGumpTTFLabel(head, 14, color)
            lb.SetRect(48, y + 2, w - 70, 18)
            sa.Add(lb)
            why = r["reason"]
            if r.get("sorted"):
                why += "  [%s]" % r["sorted"]
            elif r["tier"] in ("Unravel", "Sell", "Junk"):
                why += "  (%s)" % r["why"]
            lb2 = API.Gumps.CreateGumpTTFLabel(why, 12, DIM)
            lb2.SetRect(48, y + 20, w - 70, 16)
            sa.Add(lb2)
        y = h - 34
        self._button(g, "Rate backpack", 10, y, 100, 24, lambda: (core.rate_backpack(), self.open_results()))
        self._button(g, "Sort to bags", 116, y, 90, 24, lambda: core.sort_all())
        self._button(g, "Clear", 212, y, 60, 24, lambda: (core.rated.__delitem__(slice(None)), self.open_results()))
        self._button(g, "Refresh rank", 278, y, 90, 24, lambda: core.refresh_rank())
        self._button(g, "Close", 374, y, 60, 24, lambda: self._close(self.results))
        self.results_key = (len(core.rated), core.rated[0]["serial"] if core.rated else 0,
                            core.rated[0].get("sorted") if core.rated else "")
        self.results = self._show(g)

    # -- profile editor --------------------------------------------------------------------

    def open_profile(self, suggest=False):
        self._close(self.profile)
        s = S.SETTINGS
        name = s.get("activeProfile", "Melee starter")
        weights = dict(S.active_profile())
        caps = dict(S.profile_caps())
        w, h = 480, 560
        g = self._gump(w, h, "Profile: %s" % name, 400, 60)
        self._label(g, "Name", 10, 32, 50)
        self.profile_name_box = self._textbox(g, name, 60, 30, 220)
        self._label(g, "weight", 300, 32, 60, 18, DIM, 12)
        self._label(g, "cap", 360, 32, 60, 18, DIM, 12)
        sa = API.Gumps.CreateGumpScrollArea(0, 56, w, 300)
        g.Add(sa)
        self.profile_boxes = {}
        for i, prop in enumerate(R.property_names()):
            y = i * 24
            lb = API.Gumps.CreateGumpTTFLabel(prop, 13, TEXT)
            lb.SetRect(10, y + 3, 280, 18)
            sa.Add(lb)
            wb = API.Gumps.CreateGumpTextBox(str(weights.get(prop, 0)), 50, 20, False, 14)
            wb.SetPos(300, y)
            sa.Add(wb)
            cb = API.Gumps.CreateGumpTextBox(str(caps.get(prop, "")), 50, 20, False, 14)
            cb.SetPos(360, y)
            sa.Add(cb)
            self.profile_boxes[prop] = (wb, cb)
        self._label(g, "Suggest reads your skills and gear; Accept saves it as a new profile.", 10, 362, w - 20, 18, DIM, 12)
        self.profile_notes = self._textbox(g, "", 10, 382, w - 20, 120, True)
        y = h - 46
        self._button(g, "Save", 10, y, 70, 24, lambda: self._save_profile(False))
        self._button(g, "Save as", 86, y, 70, 24, lambda: self._save_profile(True))
        self._button(g, "Delete", 162, y, 70, 24, lambda: self._delete_profile())
        self._button(g, "Suggest", 238, y, 70, 24, lambda: self._suggest())
        self._button(g, "Accept", 314, y, 70, 24, lambda: self._accept_suggestion())
        self._button(g, "Close", 390, y, 70, 24, lambda: self._close(self.profile))
        self.profile = self._show(g)
        if suggest:
            self._suggest()

    def _read_profile_boxes(self):
        weights = {}
        caps = {}
        for prop, (wb, cb) in self.profile_boxes.items():
            weights[prop] = S.to_float(wb.Text, 0)
            c = (cb.Text or "").strip()
            if c:
                caps[prop] = S.to_float(c, 0)
        return weights, caps

    def _save_profile(self, save_as):
        weights, caps = self._read_profile_boxes()
        name = (self.profile_name_box.Text or "").strip() if save_as else S.SETTINGS.get("activeProfile")
        if not name:
            API.SysMsg("[SL_Combat] give the profile a name first", 33)
            return
        S.set_profile(name, weights, caps, select=True)
        API.SysMsg("[SL_Combat] profile saved: %s" % name, 68)
        self.open_main()
        self.open_profile()

    def _delete_profile(self):
        name = S.SETTINGS.get("activeProfile")
        if S.delete_profile(name):
            API.SysMsg("[SL_Combat] profile deleted: %s" % name, 68)
            self.open_main()
            self.open_profile()
        else:
            API.SysMsg("[SL_Combat] the Melee starter profile stays", 33)

    def _skills(self):
        out = {}
        for name in SUGGEST_SKILLS:
            try:
                sk = API.GetSkill(name)
                out[name] = float(sk.Value) if sk is not None else 0.0
            except Exception:
                out[name] = 0.0
        return out

    def _suggest(self):
        base, caps = self._read_profile_boxes()
        weights, notes = R.suggest(R.player_snapshot(), self._skills(), base)
        self.suggested = weights
        for prop, (wb, cb) in self.profile_boxes.items():
            if prop in weights:
                wb.SetText(str(weights[prop]))
        try:
            self.profile_notes.SetText("\n".join(notes))
        except Exception:
            pass
        API.SysMsg("[SL_Combat] suggestion ready: read the notes, tweak, then Accept", 68)

    def _accept_suggestion(self):
        weights, caps = self._read_profile_boxes()
        name = "Suggested %s" % time.strftime("%Y-%m-%d %H:%M")
        S.set_profile(name, weights, caps, select=True)
        API.SysMsg("[SL_Combat] profile saved and selected: %s" % name, 68)
        self.open_main()
        self.open_profile()

    # -- shutdown ------------------------------------------------------------------------

    def close_all(self):
        for g in (self.main, self.settings, self.results, self.profile):
            self._close(g)


if __name__ == "__main__":
    API.SysMsg("SL_Combat_Gump is a module of SL_Combat: run SL_Combat.py instead.", 43)
