#!/usr/bin/python

# Class to write into the Akabei SQLite database
#
#   Copyright (C) 2011 Lisa Vitolo <shainer@chakra-project.org>

#   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.

import sys
import os

from akabeiprogressbar import *

try:
    from pysqlite2 import dbapi2 as sqlite
except ImportError:
    print "[!!] You need to install the python-pysqlite package to execute this script. Quitting..."
    sys.exit(-1)
    
class AkabeiDbWriter:
    def __init__(self, dbname, dbSchemeName):
        
        # If exists, I cannot write again the scheme on it
        # so I just wipe out all the content,
        # plus I check if there are some permission problems for writing on the file
        try:
            db = open(dbname, "w")
            db.close()
        except IOError, error:
            print str(error)
            print "[!!] Error opening the database output file for writing. Quitting..."
            sys.exit(-1)
            
        print "[**] The Akabei database will be written in '" + dbname + "'"
        
        self.dbconnection = sqlite.connect(dbname)
        self.dbconnection.text_factory = str # needed for some fields
        self.dbcursor = self.dbconnection.cursor()
        
        self.writeDbScheme(dbSchemeName)
        
    # Reads the scheme file and apply it into the newly created database
    def writeDbScheme(self, dbSchemeName):
        print "[**] Setting up the database scheme from " + dbSchemeName + " ... ",
        
        try:
            dbscheme = open(dbSchemeName, "r")
        except IOError, error:
            print str(error)
            print "[!!] This script needs a database scheme file to perform the conversion."
            print "[!!] Use " + sys.argv[0] + " -s <path to the scheme> to specify a different one."
            sys.exit(-1)
            
        query = ""
        for line in dbscheme.readlines():
            if line == "\n":
                self.dbcursor.execute(query)
                query = ""
            else:
                query += line
                
        # Catch up last line
        if len(query) > 0:
            self.dbcursor.execute(query)
                
        self.dbconnection.commit()
        print "done."
        
    def addPackages(self, pkgs):
        query = ""
        
        print "[**] Writing packages on the Akabei database..."

        # See __main__.py for an explanation about how the progress bar works
        progress = 0.0
        progressReach100 = False
        step = 1.0 / (len(pkgs) / 100)
        showProgress(progress)
        
        # Insert packages into the database
        for p in pkgs:
            query = "INSERT INTO packages ("\
            "'name', 'version', 'filename', 'description', 'size',"\
            "'installedsize', 'md5sum', 'url', 'builddate', 'arch', 'packager',"\
            "'flags', 'screenshoturl', 'installreason', 'installdate') "\
            "VALUES ("\
            "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
            self.dbcursor.execute(query, (p.name, p.version, p.filename, p.description, p.size, p.installedsize, p.md5sum, p.url, p.builddate, p.arch, p.packager, p.flags, p.screenshoturl, p.installreason, p.installdate))
            pkgid = self.dbcursor.lastrowid
            
            for scriptlet in p.scriptlets:
                query = "INSERT INTO scriptlets ('package', 'scriptlet') VALUES (?, ?)"
                self.dbcursor.execute(query, (pkgid, scriptlet))
                
            for dep in p.dependencies:
                query = "INSERT INTO depends ('package', 'dependency') VALUES (?, ?)"
                self.dbcursor.execute(query, (pkgid, dep))
                
            for conflict in p.conflicts:
                query = "INSERT INTO conflicts ('package', 'conflict') VALUES (?, ?)"
                self.dbcursor.execute(query, (pkgid, conflict))
                
            for provide in p.provides:
                query = "INSERT INTO provides ('package', 'provides') VALUES (?, ?)"
                self.dbcursor.execute(query, (pkgid, provide))
                
            for opt in p.optionals:
                query = "INSERT INTO optional ('package', 'dependency') VALUES (?, ?)"
                self.dbcursor.execute(query, (pkgid, opt))
                
            for rep in p.replaces:
                query = "INSERT INTO replaces ('package', 'replaces') VALUES (?, ?)"
                self.dbcursor.execute(query, (pkgid, rep))
                
            for mime in p.mimetypes:
                query = "INSERT INTO providesmimetype ('package', 'mimetype') VALUES (?, ?)"
                self.dbcursor.execute(query, (pkgid, mime))
                
            for license in p.licenses:
                query = "INSERT INTO licensed ('package', 'license') VALUES (?, ?)"
                self.dbcursor.execute(query, (pkgid, license))
                
            for group in p.groups:
                
                # Add the group too if not already present
                if not self.groupExist(group):
                    query = "INSERT INTO groups ('name') VALUES (?)"
                    self.dbcursor.execute(query, (group,))
                
                query = "INSERT INTO belongsgroup ('package', 'groupname') VALUES (?, ?)"
                self.dbcursor.execute(query, (pkgid, group))
                
            for f in p.files:
                query = "INSERT INTO files ('package', 'file', 'backup') VALUES (?, ?, ?)"
                self.dbcursor.execute(query, (pkgid, f.name, f.backup))
                
            progress += step
            
            if progress == 100:
                progressReach100 = True
                
            if progress <= 100:
                showProgress(progress)
            
        
        if not progressReach100:
            showProgress(100)
            
        print "done."
        print "[**] Committing to database... ",
        self.dbconnection.commit()
        print "done."
        
    def groupExist(self, gname):
        query = "SELECT * FROM groups WHERE name='" + gname + "'"
        self.dbcursor.execute(query)
        
        return len(self.dbcursor.fetchall()) > 0
    
