# Copyright (C) 2008 Libresoft Research Group
#
# 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 2 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Authors : Israel Herraiz <herraiz@gsyc.escet.urjc.es>

from mydatabase import MyDatabase
import os
import commands
import sys
import re

class MyApp:

    def __init__(self,host,user,password,dbname):

        self.db = MyDatabase()

        self.db.user = user
        self.db.password = password
        self.db.host = host
        self.db.name = dbname

        self.db.connect()

    def run(self):

        # Get files to be measured
        print "Querying,,,"
        self.db.getCFiles()
        row = self.db.cursor_get.fetchone()
        while row:
            filemd5 = row[0]
            filepath = row[1]

            print "Measuring "+filepath+"..."

            list_of_dicts = self.measureMcCabe(filepath)

            for d in list_of_dicts:
                d['md5'] = filemd5
                self.db.insertFunction(d)

            row = self.db.cursor_get.fetchone()
                            


    def measureMcCabe(self,filepath):
        cmd = 'mccabe -n "'+filepath+'"'
        output = commands.getoutput(cmd)

        list_of_dicts = []

        for l in output.split('\n'):

            d = {}

            try:
                funcname = l.split('\t')[-4]
                sloc = int(l.split('\t')[-3])
                mccabe = int(l.split('\t')[-2])
                returns = int(l.split('\t')[-1])

                d['funcname'] = funcname
                d['sloc'] = sloc
                d['mccabe'] = mccabe
                d['numreturns'] = returns
                list_of_dicts.append(d)
            except:
                #print cmd
                #print output
                #sys.exit(0)
                continue

        return list_of_dicts


if '__main__' == __name__:

    host = 'localhost'
    user = 'root'
    password = 'root'
    dbname = 'metrics_tse_herraiz'
    app = MyApp(host=host, 
                user=user, 
                password=password, 
                dbname=dbname)
    app.run()

