#!/usr/bin/python
"""
Copyright (C) 2011 Konstantin Andrusenko
    See the documentation for further information on copyrights,
    or contact the author. All Rights Reserved.

@author Konstantin Andrusenko
@date November 30, 2011

operations-installer is utility for installation operations into database
"""

import yaml
import os
import sys
from blik.utils.databaseConnection import DatabaseConnection
from datetime import datetime


class Operation:
    def __init__(self, sid, name, node_type_sid, timeout, description):
        self.sid = sid
        self.name = name
        self.node_type = node_type_sid
        self.timeout = timeout
        self.description = description

def print_log(message):
    print ('[%s] %s' % (datetime.now(), message))

def _get_item(obj, element_name):
    element = obj.get(element_name, None)
    if element is None:
        raise Exception('<%s> element is not found'%element_name)

    return element

def parse_specification(yaml_file):
    url_lower = yaml_file.lower()
    if url_lower.startswith('http://') or url_lower.startswith('ftp://'):
        yaml_file_out = '/tmp/tmp-spec.yaml'

        ret,out,err = run_command(['wget', yaml_file, '-O', yaml_file_out])
        if ret:
            raise Exception('Operations specification is not downloaded! Details: %s'%err)
    else:
        yaml_file_out = yaml_file

    f = open(yaml_file)
    objects = yaml.load(f.read())
    f.close()

    operations = _get_item(objects, 'operations')
    ret_list = []
    for operation in operations:
        sid = _get_item(operation, 'sid')
        name = _get_item(operation, 'label')
        node_type = operation.get('node_type',None)
        timeout = int(_get_item(operation,'timeout'))
        description = operation.get('description', None)

        ret_list.append(Operation(sid, name, node_type, timeout, description))

    return ret_list

def insert_operations(operations):
    dbsrv = DatabaseConnection()

    for operation in operations:
        node_type_id = None
        if operation.node_type:
            rows = dbsrv.select("SELECT id FROM nm_node_type WHERE type_sid=%s",(operation.node_type,))
            if not rows:
                raise Exception('Node type "%s" is not found in database!'%operation.node_type)
            node_type_id = rows[0][0]

        rows = dbsrv.select("SELECT id FROM nm_operation WHERE sid=%s",(operation.sid,))
        if not rows:
            dbsrv.modify("INSERT INTO nm_operation (sid, name, timeout, node_type_id, description) VALUES (%s,%s,%s,%s,%s)",
                        (operation.sid, operation.name, operation.timeout, node_type_id, operation.description))
        else:
            dbsrv.modify("UPDATE nm_operation SET name=%s, timeout=%s, node_type_id=%s, description=%s WHERE id=%s",
                    (operation.name, operation.timeout, node_type_id, operation.description, rows[0][0]))


#-----------------------------------------------------------------------------------


def main(yaml_file):
    try:
        operations = parse_specification(yaml_file)

        insert_operations(operations)

        print_log('Operations installed successful!')
    except Exception, err:
        print_log(err)
        print_log('Operations installation failed!')
        return 1

    return 0

#-----------------------------------------------------------------------------------

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print 'Usage: operations-installer <yaml-file>'
        sys.exit(1)

    yaml_file = sys.argv[-1]

    ret = main(yaml_file)

    sys.exit(ret)

