#!/usr/bin/env python
# -*- coding:UTF-8 -*-
#       Copyright (c) Stephen Smally <stephen.smally@gmail.com>
#
#       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 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., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#  

usage = '''Build a sqlite3-based database from the given directory of desktop files
Usage: lubuntu-software-center-build-db [DB_PATH] [DIRECTORY] [CATEGORYFILE]'''

import sqlite3
import sys
import os
from xdg import DesktopEntry as DE
import apt_pkg

if len(sys.argv) < 4:
    print(usage)
    sys.exit()

database = sys.argv[1]
base_folder = sys.argv[2]
categories_file = open(sys.argv[3], "r")
categories = []

for lines in categories_file:
    line = lines.rstrip().split("||")
    category = line[2]
    categories.append(category)

categories.append("allpkgs")

if os.path.exists(database):
    os.remove(database)

print("Creating package database in %s" % database)

db = sqlite3.Connection(database)
cursor = db.cursor()
for items in categories:
    categ_string = "create table %s(name, pkg_name, comment, icon, deps, recs)" % items
    print(categ_string)
    cursor.execute(categ_string)
aiddir = os.listdir(base_folder)

def categs_in_cat(categs):
    for items in categs:
        if items in categories:
            return items

packages = []

apt_pkg.init()
cache = apt_pkg.Cache()
depcache = apt_pkg.DepCache(cache)

for item in aiddir:
    if item.partition(".desktop")[-2] == ".desktop":
        single_pkg = DE.DesktopEntry(base_folder+item)
        name = single_pkg.getName()
        pkg = single_pkg.get("X-AppInstall-Package")
        icon = single_pkg.getIcon()
        categs = single_pkg.getCategories()
        cat = categs_in_cat(categs)
        comment = single_pkg.getComment()
        dep_list = []
        rec_list = []
        depends_list = []
        rec = []
        try:
            if not (cache[pkg].version_list == []) and (depcache.get_candidate_ver(cache[pkg]) == None):
                version = depcache.get_candidate_ver(cache[pkg])
                try:
                    depends_list = version.depends_list_str["Depends"]
                    rec = version.depends_list_str["Recommends"]
                except:
                    depends_list = []
                    rec = []
            
            elif not cache[pkg].provides_list == []:
                for pkgs in cache[pkg].provides_list:
                    version = pkgs[2]
                    try:
                        depends_list = version.depends_list_str["Depends"]
                        rec = version.depends_list_str["Recommends"]
                    except KeyError:
                        depends_list = []
                        rec = []
        
        except KeyError:
            print("%s: package not found" % pkg)
        
        for items in depends_list:
                dep_list.append(items[0][0])
        for items in rec:
                rec_list.append(items[0][0])
        
        if comment == '':
            comment = u"No description available"
        packages.append([cat, name.capitalize(), pkg, comment, icon, "|".join(dep_list), "|".join(rec_list)])

for (cat, name, pkg, comment, icon, deps, recs) in sorted(packages, key=lambda val: val[1]):
	if cat != None:
		cursor.execute("insert into %s values(?, ?, ?, ?, ?, ?)" % cat, (name, pkg, comment, icon, deps, recs))
	cursor.execute("insert into allpkgs values(?, ?, ?, ?, ?, ?)", (name, pkg, comment, icon, deps, recs))

print("Done")
db.commit()
