#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) 2012, 2013, 2014 Martin Raspaud

# Author(s):

#   Martin Raspaud <martin.raspaud@smhi.se>

# 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 3 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, see <http://www.gnu.org/licenses/>.

"""Trollcast server.
"""

from trollcast.server import serve
import argparse
import logging
import logging.handlers
from datetime import datetime

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("config_file")
    parser.add_argument("-l", "--log", help="File to log to.")
    parser.add_argument("-m", "--mail", help="Mail to log to.")
    parser.add_argument("-v", "--verbose",
                        help="Print out debug messages also.",
                        action="store_true")

    args = parser.parse_args()

    if args.verbose:
        loglevel = logging.DEBUG
    else:
        loglevel = logging.INFO

    logging.getLogger("").setLevel(loglevel)
    if args.log:
        ch1 = logging.handlers.TimedRotatingFileHandler(args.log,
                                                        when="midnight",
                                                        backupCount=7)
    else:
        ch1 = logging.StreamHandler()

    ch1.setLevel(loglevel)

    LOG = logging.getLogger("")

    class MyFormatter(logging.Formatter):

        """New formatter with milliseconds
        """
        converter = datetime.fromtimestamp

        def formatTime(self, record, datefmt=None):
            """Format with milliseconds if no date format is given.
            """
            ct_ = self.converter(record.created)
            if datefmt:
                s__ = ct_.strftime(datefmt)
            else:
                t__ = ct_.strftime("%Y-%m-%d %H:%M:%S")
                s__ = "%s.%03d" % (t__, record.msecs)
            return s__

    formatter = MyFormatter(
        '[ %(levelname)s %(name)s %(asctime)s] %(message)s')
    ch1.setFormatter(formatter)
    LOG.addHandler(ch1)

    if args.mail:
        ch1 = logging.handlers.SMTPHandler("localhost",
                                           "trollcast@localhost",
                                           [args.mail],
                                           "Trollcast Server Error")
        ch1.setLevel(logging.CRITICAL)
        ch1.setFormatter(formatter)
        LOG.addHandler(ch1)

    LOG = logging.getLogger("trollcast_server")

    try:
        serve(args.config_file)
    finally:
        print "Thanks for using pytroll/trollcast. See you soon on www.pytroll.org!"
