# dialogs.py — add/edit a holding, and the position details dialog
#
# SPDX-License-Identifier: GPL-3.0-or-later

from gettext import gettext as _

from gi.repository import Adw, GLib, Gtk

from . import exchanges, formatting
from .chart import PriceChart
from .exchanges import EXCHANGES, get_exchange
from .model import Holding, price_looks_wrong
from .providers import PROVIDERS_BY_ID

LOOKUP_DELAY_MS = 450


def _suffix_label(text, *classes):
    label = Gtk.Label(label=text, valign=Gtk.Align.CENTER, xalign=1,
                      css_classes=["numeric", *classes], selectable=True)
    return label


def _info_row(title, value, *classes):
    row = Adw.ActionRow(title=title, use_markup=False)
    label = _suffix_label(value, *classes)
    row.add_suffix(label)
    row.value_label = label
    return row


def set_direction_class(widget, value):
    for cls in ("positive", "negative"):
        widget.remove_css_class(cls)
    cls = formatting.direction(value)
    if cls:
        widget.add_css_class(cls)


class HoldingDialog(Adw.Dialog):
    """Add a new stock, or edit shares/average price of an existing one."""

    def __init__(self, window, holding=None, exchange_id=None):
        super().__init__(content_width=440, follows_content_size=True)
        self.window = window
        self.service = window.service
        self.editing = holding
        self.quote = None
        self._lookup_source = 0
        self._lookup_generation = 0
        self._syncing = False

        self.set_title(_("Edit Position") if holding else _("Add Stock"))

        header = Adw.HeaderBar(show_start_title_buttons=False, show_end_title_buttons=False)
        cancel = Gtk.Button(label=_("_Cancel"), use_underline=True)
        cancel.connect("clicked", lambda *_: self.close())
        header.pack_start(cancel)
        self.save_button = Gtk.Button(label=_("_Save") if holding else _("_Add"),
                                      use_underline=True, sensitive=False,
                                      css_classes=["suggested-action"])
        self.save_button.connect("clicked", self._on_save)
        header.pack_end(self.save_button)
        self.set_default_widget(self.save_button)

        page = Adw.PreferencesPage()

        # -- stock
        stock = Adw.PreferencesGroup()
        self.exchange_row = Adw.ComboRow(
            title=_("Exchange"),
            model=Gtk.StringList.new([e.name for e in EXCHANGES]))
        self.exchange_row.set_selected(exchanges.exchange_index(
            holding.exchange if holding else (exchange_id or window.last_exchange)))
        self.exchange_row.connect("notify::selected", self._on_exchange_changed)
        stock.add(self.exchange_row)

        self.symbol_row = Adw.EntryRow(title=_("Ticker Symbol"))
        self.symbol_row.connect("changed", self._on_symbol_changed)
        self.symbol_row.connect("entry-activated", self._on_activate)
        stock.add(self.symbol_row)

        self.lookup_row = Adw.ActionRow(use_markup=False, subtitle_lines=2)
        self.lookup_icon = Gtk.Image(icon_name="system-search-symbolic", pixel_size=16)
        self.lookup_spinner = Adw.Spinner()
        self.lookup_status = Gtk.Stack(transition_type=Gtk.StackTransitionType.CROSSFADE)
        self.lookup_status.add_named(self.lookup_icon, "icon")
        self.lookup_status.add_named(self.lookup_spinner, "spinner")
        self.lookup_row.add_prefix(self.lookup_status)
        self.lookup_price = _suffix_label("", "dim-label")
        self.lookup_row.add_suffix(self.lookup_price)
        stock.add(self.lookup_row)
        page.add(stock)

        # -- position
        position = Adw.PreferencesGroup(title=_("Position"))
        self.shares_row = Adw.EntryRow(title=_("Number of Shares"),
                                       input_purpose=Gtk.InputPurpose.NUMBER)
        self.shares_row.connect("changed", lambda *_: self._validate())
        self.shares_row.connect("entry-activated", self._on_activate)
        position.add(self.shares_row)

        self.cost_row = Adw.EntryRow(title=_("Average Price per Share"),
                                     input_purpose=Gtk.InputPurpose.NUMBER)
        self.cost_currency = Gtk.Label(css_classes=["dim-label"])
        self.cost_row.add_suffix(self.cost_currency)
        self.cost_row.connect("changed", lambda *_: self._validate())
        self.cost_row.connect("entry-activated", self._on_activate)
        position.add(self.cost_row)

        # Non-blocking hint for typos or the wrong currency
        self.price_warning = Adw.ActionRow(use_markup=False, visible=False, subtitle_lines=2)
        self.price_warning.add_prefix(Gtk.Image(icon_name="dialog-warning-symbolic",
                                                css_classes=["warning"]))
        position.add(self.price_warning)
        page.add(position)

        toolbar = Adw.ToolbarView()
        toolbar.add_top_bar(header)
        toolbar.set_content(page)
        self.set_child(toolbar)

        if holding:
            self.exchange_row.set_sensitive(False)
            self.symbol_row.set_text(holding.display_symbol)
            self.symbol_row.set_sensitive(False)
            self.shares_row.set_text(formatting.shares(holding.shares))
            self.cost_row.set_text(formatting.plain(holding.cost))
            self.quote = self.service.quotes.get(holding.symbol)
            self._show_holding_info()
            self.set_focus(self.shares_row)
        else:
            self._show_hint()
            self.set_focus(self.symbol_row)
        self._validate()
        self.connect("closed", self._on_closed)

    # ---- state -----------------------------------------------------------

    @property
    def exchange_id(self):
        return EXCHANGES[self.exchange_row.get_selected()].id

    def _show_hint(self):
        e = get_exchange(self.exchange_id)
        self.lookup_status.set_visible_child_name("icon")
        self.lookup_icon.set_from_icon_name("system-search-symbolic")
        self.lookup_row.set_title(_("Enter a ticker symbol"))
        self.lookup_row.set_subtitle(_("For example {examples}").format(examples=e.examples))
        self.lookup_price.set_label("")
        self.cost_currency.set_label(e.currency)

    def _show_holding_info(self):
        h = self.editing
        self.lookup_status.set_visible_child_name("icon")
        self.lookup_icon.set_from_icon_name("emblem-ok-symbolic")
        self.lookup_row.set_title(h.name or h.display_symbol)
        self.lookup_row.set_subtitle(get_exchange(h.exchange).name)
        if self.quote:
            self.lookup_price.set_label(formatting.money(self.quote.price, self.quote.currency))
        self.cost_currency.set_label(h.currency or get_exchange(h.exchange).currency)

    def _validate(self):
        shares = formatting.parse_decimal(self.shares_row.get_text())
        cost = formatting.parse_decimal(self.cost_row.get_text())
        known = self.editing is not None or self.quote is not None
        for row, ok in ((self.shares_row, shares is not None and shares > 0),
                        (self.cost_row, cost is not None)):
            if row.get_text().strip() and not ok:
                row.add_css_class("error")
            else:
                row.remove_css_class("error")
        valid = known and shares is not None and shares > 0 and cost is not None
        self.save_button.set_sensitive(valid)
        self._update_price_warning(cost)
        return valid

    def _update_price_warning(self, cost):
        quote = self.quote
        if quote is None and self.editing is not None:
            quote = self.service.quotes.get(self.editing.symbol)
        if quote is None or cost is None or not price_looks_wrong(cost, quote.price):
            self.price_warning.set_visible(False)
            return
        self.price_warning.set_title(_("Far from the current price of {price}").format(
            price=formatting.money(quote.price, quote.currency)))
        self.price_warning.set_subtitle(
            _("Check that this is the price per share, in {currency}").format(
                currency=quote.currency))
        self.price_warning.set_visible(True)

    # ---- lookup ----------------------------------------------------------

    def _on_exchange_changed(self, *_args):
        if not self._syncing:
            self.window.last_exchange = self.exchange_id
            self._schedule_lookup()

    def _on_symbol_changed(self, *_args):
        if not self._syncing:
            self._schedule_lookup()

    def _schedule_lookup(self):
        self.quote = None
        self._lookup_generation += 1
        if self._lookup_source:
            GLib.source_remove(self._lookup_source)
            self._lookup_source = 0
        self._validate()
        if not self.symbol_row.get_text().strip():
            self._show_hint()
            return
        self.lookup_status.set_visible_child_name("spinner")
        self.lookup_row.set_title(_("Looking up…"))
        self.lookup_row.set_subtitle("")
        self.lookup_price.set_label("")
        self._lookup_source = GLib.timeout_add(LOOKUP_DELAY_MS, self._do_lookup)

    def _do_lookup(self):
        self._lookup_source = 0
        text = self.symbol_row.get_text()
        detected = exchanges.detect_exchange(text)
        if detected and detected != self.exchange_id:
            # "EQNR.OL" typed with NYSE selected: switch market for the user
            self._syncing = True
            self.exchange_row.set_selected(exchanges.exchange_index(detected))
            self._syncing = False
        symbol = exchanges.to_yahoo_symbol(text, self.exchange_id)
        generation = self._lookup_generation
        exchange_id = self.exchange_id
        self.service.lookup(symbol, exchange_id, lambda q, err: self._on_lookup_done(
            generation, exchange_id, symbol, q, err))
        return GLib.SOURCE_REMOVE

    def _on_lookup_done(self, generation, exchange_id, symbol, quote, error):
        if generation != self._lookup_generation:
            return
        self.lookup_status.set_visible_child_name("icon")
        e = get_exchange(exchange_id)
        if error or quote is None:
            self.lookup_icon.set_from_icon_name("dialog-warning-symbolic")
            self.lookup_row.set_title(_("“{symbol}” not found on {exchange}").format(
                symbol=exchanges.display_symbol(symbol, exchange_id), exchange=e.name))
            self.lookup_row.set_subtitle(error or "")
            return
        problem = exchanges.listing_problem(quote, exchange_id)
        if problem:
            self.lookup_icon.set_from_icon_name("dialog-warning-symbolic")
            self.lookup_row.set_title(problem)
            self.lookup_row.set_subtitle(_("Choose the exchange where the stock is listed"))
            return
        self.quote = quote
        self.service.remember(quote)
        held = self.window.portfolio.find_symbol(quote.symbol)
        self.lookup_icon.set_from_icon_name("emblem-ok-symbolic")
        self.lookup_row.set_title(quote.name)
        if held:
            self.lookup_row.set_subtitle(
                _("You already own {n} shares — these will be added to that position").format(
                    n=formatting.shares(held.shares)))
        else:
            via = PROVIDERS_BY_ID[quote.source].name if quote.source in PROVIDERS_BY_ID else ""
            self.lookup_row.set_subtitle(" · ".join(x for x in (quote.exchange_name or e.name,
                                                                via) if x))
        self.lookup_price.set_label(formatting.money(quote.price, quote.currency))
        self.cost_currency.set_label(quote.currency)
        if not self.cost_row.get_text().strip():
            self.cost_row.set_text(formatting.plain(quote.price))
        self._validate()

    # ---- saving ----------------------------------------------------------

    def _on_activate(self, *_args):
        if self._validate():
            self._on_save()

    def _on_save(self, *_args):
        if not self._validate():
            return
        shares = formatting.parse_decimal(self.shares_row.get_text())
        cost = formatting.parse_decimal(self.cost_row.get_text())
        if self.editing:
            self.window.update_holding(self.editing.id, shares, cost)
        else:
            q = self.quote
            self.window.add_holding(Holding(
                symbol=q.symbol, exchange=self.exchange_id, shares=shares, cost=cost,
                name=q.name, currency=q.currency))
        self.close()

    def _on_closed(self, *_args):
        self._lookup_generation += 1
        if self._lookup_source:
            GLib.source_remove(self._lookup_source)
            self._lookup_source = 0


RANGE_BUTTONS = (("1d", _("1D"), "%H:%M"), ("1mo", _("1M"), "%d %b"),
                 ("6mo", _("6M"), "%d %b"), ("1y", _("1Y"), "%b %Y"),
                 ("5y", _("5Y"), "%Y"))


class PositionDialog(Adw.Dialog):
    """Price chart and figures for one holding."""

    def __init__(self, window, holding_id):
        super().__init__(content_width=560, content_height=760)
        self.window = window
        self.holding_id = holding_id
        self.range_id = "1d"
        self._generation = 0
        h = window.portfolio.get(holding_id)
        e = get_exchange(h.exchange)
        self.set_title(h.name or h.display_symbol)

        header = Adw.HeaderBar()
        header.set_title_widget(Adw.WindowTitle(
            title=h.name or h.display_symbol, subtitle=f"{h.display_symbol} · {e.name}"))

        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=18,
                      margin_top=12, margin_bottom=24, margin_start=12, margin_end=12)

        # price heading
        self.price_label = Gtk.Label(xalign=0, css_classes=["title-1", "numeric"], selectable=True)
        self.change_label = Gtk.Label(xalign=0, css_classes=["numeric", "change-text"])
        self.time_label = Gtk.Label(xalign=0, css_classes=["dim-label", "caption"])
        heading = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
        for w in (self.price_label, self.change_label, self.time_label):
            heading.append(w)
        box.append(heading)

        # range selector + chart
        ranges = Gtk.Box(css_classes=["linked"], halign=Gtk.Align.CENTER, homogeneous=True)
        first = None
        for range_id, label, _fmt in RANGE_BUTTONS:
            button = Gtk.ToggleButton(label=label, active=(range_id == self.range_id))
            button.set_size_request(52, -1)
            if first:
                button.set_group(first)
            else:
                first = button
            button.connect("toggled", self._on_range_toggled, range_id)
            ranges.append(button)
        self.chart = PriceChart()
        chart_card = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12,
                             css_classes=["card", "chart-card"])
        chart_card.append(self.chart)
        chart_card.append(ranges)
        box.append(chart_card)

        # figures
        figures = Adw.PreferencesGroup(title=_("Your Position"))
        self.rows = {}
        for key, title in (("shares", _("Shares")),
                           ("cost", _("Average Price")),
                           ("basis", _("Amount Invested")),
                           ("value", _("Market Value")),
                           ("value_base", _("Market Value ({base})")),
                           ("gain", _("Total Return")),
                           ("day", _("Today"))):
            row = _info_row(title, "—")
            self.rows[key] = row
            figures.add(row)
        box.append(figures)

        # actions
        buttons = Gtk.Box(spacing=12, halign=Gtk.Align.CENTER)
        edit = Gtk.Button(label=_("_Edit Position"), use_underline=True, css_classes=["pill"])
        edit.connect("clicked", self._on_edit)
        remove = Gtk.Button(label=_("_Remove"), use_underline=True,
                            css_classes=["pill", "destructive-action"])
        remove.connect("clicked", self._on_remove)
        buttons.append(edit)
        buttons.append(remove)
        box.append(buttons)

        clamp = Adw.Clamp(maximum_size=560, child=box)
        scrolled = Gtk.ScrolledWindow(hscrollbar_policy=Gtk.PolicyType.NEVER,
                                      propagate_natural_height=True, child=clamp)
        toolbar = Adw.ToolbarView()
        toolbar.add_top_bar(header)
        toolbar.set_content(scrolled)
        self.set_child(toolbar)

        self.update()
        self._load_range()

    @property
    def holding(self):
        return self.window.portfolio.get(self.holding_id)

    def update(self):
        """Refresh the figures from the window's latest quotes and rates."""
        h = self.holding
        if h is None:
            self.close()
            return
        p = self.window.position_for(h)
        base = self.window.base_currency
        cur = p.currency or ""
        q = p.quote

        self.price_label.set_label(formatting.money(p.price, cur) if q else "—")
        if q and q.change is not None:
            self.change_label.set_label("{}  ({})  {}".format(
                formatting.signed_money(q.change, cur), formatting.percent(q.change_percent),
                _("today")))
        else:
            self.change_label.set_label("")
        set_direction_class(self.change_label, q.change if q else None)
        self.time_label.set_label(self._status_line(q))

        self.rows["value_base"].set_title(_("Market Value ({base})").format(base=base))
        self.rows["value_base"].set_visible(cur != base)
        values = {
            "shares": formatting.shares(h.shares),
            "cost": formatting.money(h.cost, cur),
            "basis": formatting.money(h.cost_basis, cur),
            "value": formatting.money(p.market_value, cur),
            "value_base": formatting.money(p.value_base, base),
            "gain": "{}  ({})".format(formatting.signed_money(p.gain, cur),
                                      formatting.percent(p.gain_percent)),
            "day": "{}  ({})".format(formatting.signed_money(p.day_change, cur),
                                     formatting.percent(p.day_percent)),
        }
        for key, text in values.items():
            self.rows[key].value_label.set_label(text)
        if q and price_looks_wrong(h.cost, q.price):
            self.rows["cost"].set_subtitle(
                _("Far from the market price. Check that it is per share and in {currency}.")
                .format(currency=cur))
            self.rows["cost"].add_css_class("warning-row")
        else:
            self.rows["cost"].set_subtitle("")
        set_direction_class(self.rows["gain"].value_label, p.gain)
        set_direction_class(self.rows["day"].value_label, p.day_change)
        if self.range_id != "1d" and self.chart.points:
            self.chart.reference = h.cost
        self.chart.queue_draw()

    def _status_line(self, q):
        if q is None:
            return _("No price available")
        parts = []
        if q.market_time:
            parts.append(_("Last trade {time}").format(time=formatting.clock(q.market_time)))
        if q.delay_minutes >= 24 * 60:
            parts.append(_("end-of-day price"))
        elif q.delay_minutes:
            parts.append(_("delayed {n} min").format(n=q.delay_minutes))
        else:
            parts.append(_("real-time"))
        if q.source in PROVIDERS_BY_ID:
            parts.append(PROVIDERS_BY_ID[q.source].name)
        if self.window.service.is_stale(q.symbol):
            parts.append(_("saved {time}, not updated").format(
                time=formatting.clock(q.fetched_at)))
        else:
            parts.append(_("fetched {time}").format(time=formatting.clock(q.fetched_at)))
        return " · ".join(parts)

    def _on_range_toggled(self, button, range_id):
        if button.get_active() and range_id != self.range_id:
            self.range_id = range_id
            self._load_range()

    def _load_range(self):
        self._generation += 1
        generation = self._generation
        h = self.holding
        cached = self.window.service.quotes.get(h.symbol)
        if self.range_id == "1d" and cached and cached.points:
            self._show_history(generation, cached, None)
            return
        self.chart.set_message(_("Loading…"))
        self.window.service.history(h.symbol, h.exchange, self.range_id,
                                    lambda q, err: self._show_history(generation, q, err))

    def _show_history(self, generation, quote, error):
        if generation != self._generation or self.holding is None:
            return
        if error or quote is None or len(quote.points) < 2:
            self.chart.set_message(error or _("No price history available"))
            return
        fmt = dict((r, f) for r, _l, f in RANGE_BUTTONS)[self.range_id]
        if self.range_id == "1d":
            self.chart.set_data(quote.points, quote.previous_close,
                                _("Prev. close"), fmt)
        else:
            self.chart.set_data(quote.points, self.holding.cost, _("Your avg."), fmt)

    def _on_edit(self, *_args):
        h = self.holding
        self.close()
        HoldingDialog(self.window, h).present(self.window)

    def _on_remove(self, *_args):
        h = self.holding
        alert = Adw.AlertDialog(
            heading=_("Remove {name}?").format(name=h.name or h.display_symbol),
            body=_("The position of {n} shares will be removed from your portfolio.").format(
                n=formatting.shares(h.shares)))
        alert.add_response("cancel", _("_Cancel"))
        alert.add_response("remove", _("_Remove"))
        alert.set_response_appearance("remove", Adw.ResponseAppearance.DESTRUCTIVE)
        alert.set_default_response("cancel")
        alert.set_close_response("cancel")
        alert.connect("response", self._on_remove_response)
        alert.present(self)

    def _on_remove_response(self, _alert, response):
        if response == "remove":
            holding_id = self.holding_id
            self.close()
            self.window.remove_holding(holding_id)

