import socket

import wx

from clarabot_nano.control.wizard import SimpleWizardPage


class AdminPasswordPage(SimpleWizardPage):
    def __init__(self, parent, has_password: bool):
        SimpleWizardPage.__init__(
            self,
            parent,
            gettext(
                "The admin password for this instance of Nano provides an additional layer of security. "
                "It will be required for remote management requests. "
                "It may limit the damage an adversary will do if the owner's account gets stolen."
            ),
        )
        self._old = has_password

        self.radio_keep = wx.RadioButton(self, wx.ID_ANY, gettext("Keep current password"), style=wx.RB_GROUP)
        self.layout.Add(self.radio_keep, 0, wx.EXPAND | wx.BOTTOM, 8)
        self.radio_replace = wx.RadioButton(self, wx.ID_ANY, gettext("Replace current password"))
        self.layout.Add(self.radio_replace, 0, wx.EXPAND | wx.BOTTOM, 8)

        self.password_layout = wx.BoxSizer(wx.VERTICAL)
        self.layout.Add(self.password_layout, 0, wx.EXPAND | wx.LEFT, 16)

        self.pw = wx.TextCtrl(self, wx.ID_ANY, style=wx.TE_PASSWORD)
        self.pw.SetHint(gettext("Enter a new password"))
        self.password_layout.Add(self.pw, 0, wx.EXPAND | wx.BOTTOM | wx.LEFT, 8)
        self.pw_check = wx.TextCtrl(self, wx.ID_ANY, style=wx.TE_PASSWORD)
        self.pw_check.SetHint(gettext("Repeat the new password"))
        self.password_layout.Add(self.pw_check, 0, wx.EXPAND | wx.BOTTOM | wx.LEFT, 8)

        self.Bind(wx.EVT_RADIOBUTTON, self._on_radio_button, self.radio_keep)
        self.Bind(wx.EVT_RADIOBUTTON, self._on_radio_button, self.radio_replace)

        if self._old:
            self.radio_keep.SetValue(True)
        else:
            self.radio_replace.SetValue(True)
            self.radio_keep.Enable(False)

        self._on_radio_button()

    def _on_radio_button(self, *args):
        replace_selected = self.radio_replace.GetValue()
        self.pw.Show(replace_selected)
        self.pw_check.Show(replace_selected)
        self.Layout()

    def get_new_config(self):
        if self.radio_keep.GetValue():
            return self._old, True
        pw = self.pw.GetValue()
        if pw != self.pw_check.GetValue():
            return self._old, False
        return self._old, pw
