#!/usr/bin/python2.7 -tt

"""
Copyright (c) 2011-2013 by Johannes Findeisen and Rafael Timmerberg

This file is part of Linspector (http://linspector.org).

Linspector is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""


__version__ = "0.11.2"
__default_config__ = "./examples/minimal.json"

import argparse
import datetime
import logging
import logging.handlers
import os
import os.path as path

from linspector.backends.jsonrpc import JsonrpcBackend
from linspector.config.parser import FullConfigParser
from linspector.core.interface import LinspectorInterface
from linspector.core.job import Job
from linspector.core.scheduler import Scheduler
from linspector.frontends.lish import LishFrontend

logger = logging.getLogger(__name__)


def parse_args():
    parser = argparse.ArgumentParser(
        description="Linspector is for monitoring the vital information of hosts, services and devices in a network.",
        epilog="linspector is not some program expecting computers to run! Visit http://linspector.org for more "
               "information.",
        prog="linspector")

    #TODO: add --nocolor to disable colored output in lish
    parser.add_argument("--version", action="version", version="%(prog)s " + str(__version__))
    #TODO: make the config file a required field without -c or --config at the end eg: linspector config.json
    parser.add_argument("-c", "--config", default=__default_config__, metavar="FILE",
                        help="select configfile to use")
    parser.add_argument("-l", "--logfile", default="./log/linspector.log", metavar="FILE",
                        help="set logfile to use")

    output = parser.add_mutually_exclusive_group()
    output.add_argument("-q", "--quiet", action="store_const", dest="loglevel", const=logging.ERROR,
                        help="output only errors")
    output.add_argument("-w", "--warning", action="store_const", dest="loglevel", const=logging.WARNING,
                        help="output warnings")
    output.add_argument("-v", "--verbose", action="store_const", dest="loglevel", const=logging.INFO,
                        help="output info messages")
    output.add_argument("-d", "--debug", action="store_const", dest="loglevel", const=logging.DEBUG,
                        help="output debug messages")
    output.set_defaults(loglevel=logging.INFO)
    return parser.parse_args()


def handle_job(jobInfo):
    jobInfo.handle_call()


def main():
    args = parse_args()

    logfile = path.expanduser(args.logfile)
    if not path.exists(path.dirname(logfile)):
        os.makedirs(path.dirname(logfile))

    root_logger = logging.getLogger()

    formatter = logging.Formatter(logging.BASIC_FORMAT)
    handler = logging.handlers.RotatingFileHandler(args.logfile, maxBytes=10485760, backupCount=4)
    handler.setFormatter(formatter)

    root_logger.addHandler(handler)
    root_logger.setLevel(args.loglevel)

    try:
        config_parser = FullConfigParser()
        linspector_configuration, core = config_parser.parse_config(args.config)
    except Exception, msg:
        print("Configuration error: " + str(msg) + "; Exiting now.")
        logger.error(msg)
        exit()

    scheduler = Scheduler({"apscheduler.threadpool.max_threads": 1000})
    scheduler.start()

    start_date = datetime.datetime.now()
    time_delta = 0
    jobs = []
    for layout in linspector_configuration.get_enabled_layouts():
        for hostgroup in layout.get_hostgroups():
            for service in hostgroup.get_services():
                for host in hostgroup.get_hosts():
                    for period in service.get_periods():
                        time_delta += 2.315379
                        new_start_date = start_date + datetime.timedelta(seconds=time_delta)
                        job = Job(service,
                                  host,
                                  hostgroup.get_members(),
                                  hostgroup.get_processors(),
                                  core,
                                  hostgroup)
                        scheduler_job = period.createJob(scheduler, job, handle_job, start_date=new_start_date)
                        if scheduler_job is not None:
                            job.set_job(scheduler_job)
                            jobs.append(job)

    interface = LinspectorInterface(jobs, scheduler, linspector_configuration)

    if "jsonrpc_backend" in core and core["jsonrpc_backend"]:
        jsonrpc = JsonrpcBackend(interface, core)
        jsonrpc.daemon = True
        jsonrpc.start()

    LishFrontend(interface)

    logger.debug("shutting down scheduler")

    shutdown_wait = True
    if "shutdown_wait" in core:
        shutdown_wait = core["shutdown_wait"]

    scheduler.shutdown(wait=shutdown_wait)
    logging.shutdown()


if __name__ == "__main__":
    main()