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

# Copyright (c) 2012, 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 client.
"""

import logging
import logging.handlers
from datetime import datetime
from trollcast.client import Client
import argparse

logger = logging.getLogger(__name__)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("-t", "--times", nargs=2,
                        help="Start and end times, <YYYYMMDDHHMMSS>")
    parser.add_argument("-o", "--output",
                        help="Output file (used only in conjuction with -t)")
    parser.add_argument("-f", "--config_file", required=True,
                        help="eg. sattorrent_local.cfg")
    parser.add_argument("satellite", nargs="+", help="eg. noaa_18")
    parser.add_argument("-l", "--log", help="File to log to.")
    parser.add_argument("-v", "--verbose",
                        help="Print out debug messages also.",
                        action="store_true")
    args = parser.parse_args()
    if args.log:
        ch1 = logging.handlers.TimedRotatingFileHandler(args.log,
                                                        when="midnight",
                                                        backupCount=7)
    else:
        ch1 = logging.StreamHandler()
    ch1.setLevel(logging.DEBUG)
    ch2 = logging.handlers.SMTPHandler("localhost", "martin.raspaud@smhi.se",
                                       ["martin.raspaud@smhi.se",
                                           "janne.kotro@fmi.fi"],
                                       "Trollcast client problem")
    ch2.setLevel(logging.CRITICAL)
    formatter = logging.Formatter(
        '[%(levelname)s %(name)s %(asctime)s] %(message)s')
    ch1.setFormatter(formatter)
    ch2.setFormatter(formatter)
    logging.getLogger('').addHandler(ch1)
    logging.getLogger('').addHandler(ch2)
    if args.verbose:
        logging.getLogger('').setLevel(logging.DEBUG)
    else:
        logging.getLogger('').setLevel(logging.INFO)
    logging.getLogger('posttroll.message_broadcaster').setLevel(logging.INFO)
    logger = logging.getLogger("trollcast_client")

    times = args.times

    client = Client(args.config_file)
    client.start()

    try:
        if times:
            start_time = datetime.strptime(times[0], "%Y%m%d%H%M%S")
            end_time = datetime.strptime(times[1], "%Y%m%d%H%M%S")

            time_slice = slice(start_time, end_time)
            platform = " ".join(args.satellite[0].split("_")).upper()
            client.order(time_slice, platform, args.output)
        else:
            platforms = [" ".join(plat.split("_")).upper()
                         for plat in args.satellite]

            client.get_all(platforms)
    except KeyboardInterrupt:
        pass

    finally:
        client.stop()
        print ("Thanks for using pytroll/trollcast. "
               "See you soon on www.pytroll.org!")
