import unittest
from unittest.mock import patch

import api.v1.spamcheck_pb2 as spam

from app.issue import Spammable, Issue


class TestSpam(unittest.TestCase):
    mock_issue = {
        "title": "mock spam",
        "description": "mock spam",
        "user_in_project": False,
        "project": {
            "project_id": 555,
            "project_path": "mockj/spmmable",
        },
        "user": {
            "emails": [{"email": "test@example.com", "verified": True}],
            "username": "test",
            "org": "test",
        },
    }

    def test_project_allowed(self):
        mock_project = {123: "spamtest/hello"}
        s = Issue(spam.Issue(**self.mock_issue), None)

        allowed = s.project_allowed(555)
        self.assertEqual(True, allowed, "Empty allow and deny list should return True")

        s.allow_list = mock_project
        allowed = s.project_allowed(555)
        self.assertEqual(
            False, allowed, "Project not in allow_list should return False"
        )

        allowed = s.project_allowed(123)
        self.assertEqual(True, allowed, "Project in allow_list should return True")

        s.allow_list = {}
        s.deny_list = mock_project
        allowed = s.project_allowed(555)
        self.assertEqual(True, allowed, "Project not in deny_list should return True")

        allowed = s.project_allowed(123)
        self.assertEqual(False, allowed, "Project in deny_list should return False")

    def test_email_allowed(self):
        def set_emails(email, verified):
            args = {"user": {"emails": [{"email": email, "verified": verified}]}}
            i = spam.Issue(**args)
            return i.user.emails

        s = Issue(spam.Issue(**self.mock_issue), None)
        Spammable.allowed_domains = {"gitlab.com"}
        emails = set_emails("integrationtest@example.com", True)
        allowed = s.email_allowed(emails)
        self.assertEqual(False, allowed, "Non gitlab email should not be allowed")

        emails = set_emails("integrationtest@gitlab.com", True)
        allowed = s.email_allowed(emails)
        self.assertEqual(True, allowed, "Verified gitlab email should be allowed")

        emails = set_emails("integrationtest@gitlab.com", False)
        allowed = s.email_allowed(emails)
        self.assertEqual(
            False, allowed, "Non-verified gitlab email should not be allowed"
        )
