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

import os
import time
import traceback

from flask import g, current_app

from app import email

"""Simple & stupid file logguer, used only to debug
   (logging to SQL is done in scolog)
"""

LOG_FILENAME = "notes.log"  # empty to disable logging
DEFAULT_LOG_DIR = (
    "/opt/scodoc-data/log"  # clients should call set_log_directory to change this
)

ALARM_DESTINATION = "emmanuel@scodoc.org"


class _logguer(object):
    def __init__(self):
        self.file = None
        self.directory = None
        self.set_log_directory(DEFAULT_LOG_DIR)

    def set_log_directory(self, directory):
        if self.directory != directory and self.file:
            # changing directory when a log is already open: close it
            self.file.close()
            self.file = None
        self.directory = directory

    def _open(self):
        if LOG_FILENAME:
            path = os.path.join(self.directory, LOG_FILENAME)
            self.file = open(path, "a")
            self("new _logguer (%s)" % path)
        else:
            self.file = None  # logging disabled

    def __call__(self, msg):
        if not self.file:
            self._open()
        if self.file:
            try:
                dept = getattr(g, "scodoc_dept", "")
            except RuntimeError:
                # Flask Working outside of application context.
                dept = ""
            if dept:
                dept = " (%s)" % dept
            msg = dept + " " + msg
            self.file.write("[%s]%s\n" % (time.strftime("%a %b %d %H:%M:%S %Y"), msg))
            if current_app:
                current_app.logger.info(msg)

            self.file.flush()


log = _logguer()


# Alarms by email:
def sendAlarm(subject, txt):
    from app.scodoc import sco_preferences

    sender = sco_preferences.get_preference("email_from_addr")
    email.send_email(subject, sender, [ALARM_DESTINATION], txt)


# Debug: log call stack
def logCallStack():
    log("Call stack:\n" + "\n".join(x.strip() for x in traceback.format_stack()[:-1]))
