# -*- mode: python -*-
# -*- coding: utf-8 -*-

##############################################################################
#
# Gestion scolarite IUT
#
# Copyright (c) 1999 - 2021 Emmanuel Viennet.  All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   Emmanuel Viennet      emmanuel.viennet@viennet.net
#
##############################################################################

"""Gestion des emails
"""

from flask import request


# XXX WIP: à ré-écrire pour ScoDoc 8 (étaient des méthodes de ZScoDoc)
import os
import time

# from email.MIMEMultipart import (  # pylint: disable=no-name-in-module,import-error
#     MIMEMultipart,
# )
# from email.MIMEText import MIMEText  # pylint: disable=no-name-in-module,import-error
# from email.MIMEBase import MIMEBase  # pylint: disable=no-name-in-module,import-error
# from email.Header import Header  # pylint: disable=no-name-in-module,import-error
# from email import Encoders  # pylint: disable=no-name-in-module,import-error

import app.scodoc.sco_utils as scu
from app.scodoc.notes_log import log
import sco_version


def sendEmail(msg):  # TODO A REECRIRE ScoDoc8
    """Send an email to the address using the mailhost, if there is one."""
    raise NotImplementedError()
    try:
        mail_host = xxx.MailHost
    except:
        log("warning: sendEmail: no MailHost found !")
        return
    # a failed notification shouldn't cause a Zope error on a site.
    try:
        mail_host.send(msg.as_string())
        log("sendEmail: ok")
    except Exception as e:
        log("sendEmail: exception while sending message")
        log(e)
        pass


def sendEmailFromException(msg):
    # Send email by hand, as it seems to be not possible to use Zope Mail Host
    # from an exception handler (see https://bugs.launchpad.net/zope2/+bug/246748)
    log("sendEmailFromException")
    try:
        p = os.popen("sendmail -t", "w")  # old brute force method
        p.write(msg.as_string())
        exitcode = p.close()
        if exitcode:
            log("sendmail exit code: %s" % exitcode)
    except:
        log("an exception occurred sending mail")


def send_debug_alert(txt, REQUEST=None):
    """Send an alert email (bug report) to ScoDoc developpers"""
    if not scu.SCO_EXC_MAIL:
        log("send_debug_alert: email disabled")
        return
    if REQUEST:
        txt = _report_request(REQUEST) + txt
        URL = REQUEST.URL
    else:
        URL = "send_debug_alert"
    msg = MIMEMultipart()
    subj = Header("[scodoc] exc %s" % URL, scu.SCO_ENCODING)
    msg["Subject"] = subj
    recipients = [scu.SCO_EXC_MAIL]
    msg["To"] = " ,".join(recipients)
    msg["From"] = "scodoc-alert"
    msg.epilogue = ""
    msg.attach(MIMEText(txt, "plain", scu.SCO_ENCODING))
    sendEmailFromException(msg)
    log("Sent mail alert:\n" + txt)


def _report_request(REQUEST, fmt="txt"):
    """string describing current request for bug reports"""
    QUERY_STRING = REQUEST.QUERY_STRING
    if QUERY_STRING:
        QUERY_STRING = "?" + QUERY_STRING
    if fmt == "txt":
        REFERER = request.referrer
        HTTP_USER_AGENT = request.user_agent
    else:
        REFERER = "na"
        HTTP_USER_AGENT = "na"

    params = dict(
        AUTHENTICATED_USER=REQUEST.AUTHENTICATED_USER,
        dt=time.asctime(),
        URL=REQUEST.URL,
        QUERY_STRING=QUERY_STRING,
        METHOD=request.method,
        REFERER=REFERER,
        HTTP_USER_AGENT=HTTP_USER_AGENT,
        form=REQUEST.form,
        HTTP_X_FORWARDED_FOR="?",
        SCOVERSION=sco_version.SCOVERSION,
    )
    txt = (
        """
Version: %(SCOVERSION)s
User:    %(AUTHENTICATED_USER)s
Date:    %(dt)s
URL:     %(URL)s%(QUERY_STRING)s
Method:  %(METHOD)s

REFERER: %(REFERER)s
Form: %(form)s
Origin: %(HTTP_X_FORWARDED_FOR)s
Agent: %(HTTP_USER_AGENT)s
"""
        % params
    )
    if fmt == "html":
        txt = txt.replace("\n", "<br/>")
    return txt