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"
        )

        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: bool = True):
        self.lineEdit_nom.clear()
        self.lineEdit_prenom.clear()

        if ok:
            self.lineEdit_mail.setText("Done! Thank you for your interest")
            self.lineEdit_mail.setStyleSheet("color: green;")
        else:
            self.lineEdit_mail.setText("Oops! Something went wrong")
            self.lineEdit_mail.setStyleSheet("color: red;")

        QgsApplication.processEvents()

    def _send_email(self):

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

        ok = True if r in ["Lead already exists", "It's ok !"] else False
        self._update_text(ok)
        time.sleep(3)
        self.close()
