# Copyright (c) 2021 elParaguayo
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# Widget specific tests

import sys
from types import ModuleType

import pytest

from libqtile.bar import Bar


def no_op(*args, **kwargs):
    pass


class FakeIMAP(ModuleType):
    class IMAP4_SSL:  # noqa: N801
        def __init__(self, *args, **kwargs):
            pass

        def login(self, username, password):
            self.username = username
            self.password = password

        def status(self, path, *args, **kwargs):
            if not (self.username and self.password):
                return False, None

            return (
                "OK",
                ['"{}" (UNSEEN 2)'.format(path).encode()]
            )

        def logout(self):
            pass


class FakeKeyring(ModuleType):
    valid = True
    error = True

    def get_password(self, app, user):
        if self.valid:
            return "password"

        else:
            if self.error:
                return "Gnome Keyring Error"
            return None


def test_imapwidget(fake_qtile, monkeypatch, fake_window):
    monkeypatch.setitem(sys.modules, "imaplib", FakeIMAP("imaplib"))
    monkeypatch.setitem(sys.modules, "keyring", FakeKeyring("keyring"))
    from libqtile.widget import imapwidget

    imap = imapwidget.ImapWidget(user="qtile")
    fakebar = Bar([imap], 24)
    fakebar.window = fake_window
    fakebar.width = 10
    fakebar.height = 10
    fakebar.draw = no_op
    imap._configure(fake_qtile, fakebar)
    text = imap.poll()
    assert text == "INBOX: 2"


def test_imapwidget_keyring_error(fake_qtile, monkeypatch, fake_window):
    monkeypatch.setitem(sys.modules, "imaplib", FakeIMAP("imaplib"))
    monkeypatch.setitem(sys.modules, "keyring", FakeKeyring("keyring"))
    from libqtile.widget import imapwidget
    imapwidget.keyring.valid = False

    imap = imapwidget.ImapWidget(user="qtile")
    fakebar = Bar([imap], 24)
    fakebar.window = fake_window
    fakebar.width = 10
    fakebar.height = 10
    fakebar.draw = no_op
    imap._configure(fake_qtile, fakebar)
    text = imap.poll()
    assert text == "Gnome Keyring Error"


# Widget does not handle "password = None" elegantly.
# It logs a message but doesn't set self.password.
# The widget will then fail when it looks up this attribute and then
# fail again when it tries to return self.text.
# TO DO: Fix widget's handling of this scenario.
def test_imapwidget_password_none(fake_qtile, monkeypatch, fake_window):
    monkeypatch.setitem(sys.modules, "imaplib", FakeIMAP("imaplib"))
    monkeypatch.setitem(sys.modules, "keyring", FakeKeyring("keyring"))
    from libqtile.widget import imapwidget
    imapwidget.keyring.valid = False
    imapwidget.keyring.error = False

    imap = imapwidget.ImapWidget(user="qtile")
    fakebar = Bar([imap], 24)
    fakebar.window = fake_window
    fakebar.width = 10
    fakebar.height = 10
    fakebar.draw = no_op
    imap._configure(fake_qtile, fakebar)
    with pytest.raises(AttributeError):
        with pytest.raises(UnboundLocalError):
            imap.poll()

@@ -1120,16 +1120,45 @@
 ort sys%0A
+from importlib import reload%0A
 from typ
@@ -2085,66 +2085,182 @@
 e%0A%0A%0A
-def test_imapwidget(fake_qti
+@pytest.fixture()%0Adef patched_imap(monkeypatch):%0A    monkeypatch.delitem(sys.modu
 le
+s
 , 
-monkeypatch, fake_window):
+%22imaplib%22, raising=False)%0A    monkeypatch.delitem(sys.modules, %22keyring%22, raising=False)
 %0A   
@@ -2440,38 +2440,158 @@
 pwidget%0A
-%0A
     
-imap = imapwidget
+reload(imapwidget)%0A    yield imapwidget%0A%0A%0Adef test_imapwidget(fake_qtile, monkeypatch, fake_window, patched_imap):%0A    imap = patched_imap
 .ImapWid
@@ -2913,209 +2913,41 @@
 ndow
-):%0A    monkeypatch.setitem(sys.modules, %22imaplib%22, FakeIMAP(%22imaplib%22))%0A    monkeypatch.setitem(sys.modules, %22keyring%22, FakeKeyring(%22keyring%22))%0A    from libqtile.widget import imapwidget%0A    imapwidget
+, patched_imap):%0A    patched_imap
 .key
@@ -2957,33 +2957,32 @@
 g.valid = False%0A
-%0A
     imap = imapw
@@ -2972,34 +2972,36 @@
 %0A    imap = 
-imapwidget
+patched_imap
 .ImapWidget(
@@ -3601,209 +3601,41 @@
 ndow
-):%0A    monkeypatch.setitem(sys.modules, %22imaplib%22, FakeIMAP(%22imaplib%22))%0A    monkeypatch.setitem(sys.modules, %22keyring%22, FakeKeyring(%22keyring%22))%0A    from libqtile.widget import imapwidget%0A    imapwidget
+, patched_imap):%0A    patched_imap
 .key
@@ -3657,26 +3657,28 @@
 lse%0A    
-imapwidget
+patched_imap
 .keyring
@@ -3704,26 +3704,28 @@
  imap = 
-imapwidget
+patched_imap
 .ImapWid

Fix imapwidget test