#!/usr/bin/env python
#
# Copyright (c) 2016 Samsung Electronics.Co.Ltd.
#
# 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; version 2 of the License
#
# 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.
#
"""Access to buildmonitor database"""

import os
import sys
import MySQLdb

INVALID_ID = 0

def get_multi_values_from_query_data(query, data, verbose=True):
    try:
        if verbose:
            print 'query(%s), data(%s)' % (query, data)

        cursor = conn.cursor()
        cursor.execute(query, data)
        ret_rows = cursor.fetchall()
        if verbose:
            print 'ret_rows(%s)' % (ret_rows,)
        conn.commit()
        cursor.close()

        if not ret_rows:
            ret_rows = (INVALID_ID,)
            print 'prevent null ret_rows(%s)' % (ret_rows,)

        return ret_rows

    except MySQLdb.IntegrityError as err:
        print 'Error %d: %s' % (err.args[0], err.args[1])

def get_value_from_query_data(query, data):
    try:
        print 'query(%s), data(%s)' % (query, data)

        cursor = conn.cursor()
        cursor.execute(query, data)
        ret_id = cursor.fetchone()
        print 'ret_id(%s)' % (ret_id,)
        conn.commit()
        cursor.close()

        if not ret_id:
            ret_id = INVALID_ID
            print 'prevent null ret_id(%s)' % (ret_id,)
            return ret_id
        else:
            return ret_id[0]

    except MySQLdb.IntegrityError as err:
        print 'Error %d: %s' % (err.args[0], err.args[1])

def do_many_query(query, data):
    try:
        cursor = conn.cursor()
        cursor.executemany(query, data)
        conn.commit()
        cursor.close()
    except MySQLdb.IntegrityError as err:
        print 'Error %d: %s' % (err.args[0], err.args[1])

def do_query(query, data):
    try:
        # skip print bcz of too many logs
        if not query.startswith('INSERT INTO build_snapshot_package'):
            print 'query(%s), data(%s)' % (query, data)

        cursor = conn.cursor()
        cursor.execute(query, data)
        conn.commit()
        cursor.close()
    except MySQLdb.IntegrityError as err:
        print 'Error %d: %s' % (err.args[0], err.args[1])

def connect_db():
    global conn
    conn = 0

    try:
        print '=====[BuildMonitor DB connecting...]=====\n'

        # load config data
        db_ip = os.getenv("BUILDMONITOR_IP")
        db_user = os.getenv("BUILDMONITOR_USER")
        db_pass = os.getenv("BUILDMONITOR_PASS")
        db_name = os.getenv("BUILDMONITOR_NAME")
        print '%s %s %s' % (db_ip, db_user, db_name)

        # MySQL connect & get version
        conn = MySQLdb.connect(db_ip, db_user, db_pass, db_name, connect_timeout=3)
        cursor = conn.cursor()
        query = "SELECT VERSION()"
        version = ''
        cursor.execute(query)
        for (version) in cursor:
            print 'MySQL version: %s' % version
        cursor.close()
        return conn

    except MySQLdb.IntegrityError as err:
        print 'Error %d: %s' % (err.args[0], err.args[1])
        sys.exit(1)

def disconnect_db():
    if conn:
        conn.close()
