#!/usr/bin/env python
# -*- mode: python; coding: koi8-r; -*-

from config import program_version, bookmarks_file, filetypes_file, config_file, config_dir
import os, string, shelve
import bookmarks

def createbackup(filename):
    print 'create backup:', filename
    bs = 1024

    inf = open(filename)
    outf = open(filename+'.bak', 'w')
    d = inf.read(bs)
    while d:
        outf.write(d)
        d = inf.read(bs)


def recreatedb():

##     # for backward compatible
##     if not os.path.exists(bookmarks_file):
##         try:
##             createbackup(filetypes_file)
##             os.remove(filetypes_file)
##         except:
##             pass
##         return

    try:
        os.mkdir(config_dir)
    except:
        pass

    bookmarks_db = shelve.open(bookmarks_file)
    if not bookmarks_db.has_key('bookmarks_db_version') \
       or bookmarks_db['bookmarks_db_version'] != '0.4.6':
        bookmarks_db.close()
        return

    # σΥΒ αΧΗ  7 23:37:20 MSD 2004
    # new struct of db

    print 'recreate db...'

    createbackup(bookmarks_file)
    try:
        createbackup(filetypes_file)
        os.remove(filetypes_file)
    except:
        pass

    categories_list = bookmarks_db['categories_list']
    new_categories_list = {}
    books_list = []
    titles_list = {}

    for cat in categories_list:
        new_categories_list[cat] = []
        for b in categories_list[cat]:

            books_list.append(b.filename)
            titles_list[b.filename] = b.get_title()
            new_categories_list[cat].append(b.filename)
            if cat not in b.genres:
                b.categories = [cat] + b.genres
                b.genres = b.categories
            else:
                b.categories = b.genres
            for c in b.categories:
                if not new_categories_list.has_key(c):
                    new_categories_list[c] = []
                if b.filename not in new_categories_list[c]:
                    new_categories_list[c].append(b.filename)

            #  fix file type names
            if b.file_type == 'html_parser':
                b.file_type = 'html'
            if b.file_type == 'fb2_parser':
                b.file_type = 'fb2'

            bookmarks_db[b.filename] = b

    bookmarks_db['categories_list'] = new_categories_list
    bookmarks_db['books_list'] = books_list
    bookmarks_db['titles_list'] = titles_list
    bookmarks_db['bookmarks_db_version'] = program_version

    def get_current_book():
        try:
            fd = open(config_file)
        except:
            return None
        flag = 0
        for line in fd.readlines():
            if line == '[pybookreader]\n':
                flag = 1
                continue
            elif line[0] == '[':
                flag = 0
            elif flag == 1:
                indx = line.find('=')
                if indx == -1:
                    continue
                if line[0:indx] == 'filename':
                    return line[indx+1:-1]

    current_book = get_current_book()
    bookmarks_db['current_book'] = current_book


    bookmarks_db.close()

    print '... ok'


if __name__ == '__main__':
    recreatedb()

