import time

import requests
from qgis.core import QgsApplication
from qgis.PyQt.QtWidgets import QDialog
from qgis.PyQt.uic import loadUi

from openlog.__about__ import DIR_PLUGIN_ROOT

API_URL = "http://paixdgu.cluster029.hosting.ovh.net/cgi-bin/api.py/email"


class WelcomeScreen(QDialog):
    def __init__(self):
        """
        'Splash' screen for newsletter inscription.
        """
        super(WelcomeScreen, self).__init__()
        loadUi(str(DIR_PLUGIN_ROOT / "gui" / "welcome" / "welcome.ui"), self)
        bg_path = str(
            DIR_PLUGIN_ROOT / "resources" / "images" / "openlog_splashscreen (5).png"
        )
        bg_path = bg_path.replace("\\", "/")
        self.setStyleSheet(
            f"QDialog {{ background-image: url({bg_path}) stretch; opacity: 0;}}"
        )
        self.setFixedSize(800, 600)
        self.pushButton.clicked.connect(self._clicked)
        self.subscribe.setEnabled(False)
        self.subscribe.clicked.connect(self._send_email)
        self.lineEdit_mail.textEdited.connect(self._email_changed)

    def _clicked(self):
        self.close()

    def _email_changed(self):
        """
        Subscribe button should be enabled if text contains '@'
        """
        edited_text = self.lineEdit_mail.text()
        if edited_text.find("@") != -1:
            self.subscribe.setEnabled(True)
        else:
            self.subscribe.setEnabled(False)

    def _update_text(self, ok: int = 0):
        self.lineEdit_nom.clear()
        self.lineEdit_prenom.clear()

        if ok == 0:
            self.lineEdit_mail.setText("Done! Thank you for your interest")
            self.lineEdit_mail.setStyleSheet("color: green;")
        elif ok == 1:
            self.lineEdit_mail.setText("Please try again in a few minutes")
            self.lineEdit_mail.setStyleSheet("color: orange;")
        else:
            self.lineEdit_mail.setText("Oops! Please contact us")
            self.lineEdit_mail.setStyleSheet("color: red;")

        QgsApplication.processEvents()

    def _send_email(self):
        # feedback

        try:
            r = requests.post(
                url=API_URL,
                json={
                    "nom": self.lineEdit_nom.text(),
                    "prenom": self.lineEdit_prenom.text(),
                    "mail": self.lineEdit_mail.text(),
                },
                timeout=10,
            ).text
        except TimeoutError:
            r = "too long"

        except Exception:
            r = ""

        if r in ["Lead already exists", "It's ok !"]:
            ok = 0
        elif r in ["too long", "Spam"]:
            ok = 1
        else:
            ok = 2

        self._update_text(ok)
        time.sleep(3)
        self.close()
