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

"""
Main program of the Client written for CIRCLE Cloud.
The Client job is to help the ease of use of the cloud system.
"""

import platform
import argparse
import logging
import os
from time import gmtime, strftime


class Struct:
    """
    A struct used for parameter passing

    Keyword arguments:
    state    -- State of the Virtual Computer (running, etc..)
    protocol -- SSH, NX and RDP possible
    host     -- Address of the Virtual Computer
    port     -- The port where we can access the Virtual Computer
    user     -- Username used for the connection
    password -- Password used for the connection
    """
    pass


def parse_arguments():
    """
    Argument parser, based on the argparse module

    Keyword arguments:
    @return args -- arguments given by console
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "uri", type=str, help="Specific schema handler", nargs='?',
        default=None)
    parser.add_argument(
        "-l", "--loglevel",
        help="The level of logging severity", type=str,
        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
        default="INFO")
    parser.add_argument(
        "-f", "--logfile",
        help="Explicit location of the wanted logfile location and name",
        type=str,
        default=("%(directory)s\\%(file)s" % {
            'directory': os.path.dirname(os.path.abspath(__file__)),
            'file': 'client.log'}))
    args = parser.parse_args()
    return args


def main():
    """
    Main program
    """
    args = parse_arguments()
    logging.basicConfig(filename='%s' % args.logfile,
                        format='%(levelname)s:%(message)s')
    logger = logging.getLogger()
    logger.setLevel(args.loglevel)
    logger.info("----------------------------")
    logger.info("Client started running at %s",
                strftime("%Y-%d-%m %H:%M:%S GMT", gmtime()))
    try:

        if args.uri is not None:
            logger.info('Received the following URI: %s', args.uri)
            vm = Struct()
            x, vm.protocol, vm.user, vm.password, vm.host, vm.port = \
                args.uri.split(':', 5)
            vm.protocol = vm.protocol.upper()
            logger.debug("The Client split it followingly: protocol -> %s | "
                         "user -> %s | password -> %s | "
                         "host -> %s | port -> %s",
                         vm.protocol, vm.user, vm.password, vm.host, vm.port)
        else:
            logger.critical("Client did not receive an URI which would be "
                            "necessary to continue")
        if platform.system() == "Linux":
            logger.debug('Linux OS found, proceeding to connect methods')
            from cloud_connect_from_linux import connect
        elif platform.system() == "Windows":
            logger.debug('Windows OS found, proceeding to connect methods')
            from cloud_connect_from_windows import connect
        connect(vm)
    except:
        logger.exception("An exception was raised before connect methods"
                         "could be invoked")
        print "Unknown error occurred! Please contact the developers!"


if __name__ == "__main__":
    main()
