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

import sys
import os
import locale
import shelve
from pprint import pprint
try:
    import pybookreader
except ImportError:
    # search pybookreader module
    for p in sys.path:
        d = os.path.normpath(os.path.join(os.path.abspath(p), '..'))+os.sep
        f = os.path.join(d, 'pybookreader', '__init__.py')
        if os.path.exists(f):
            sys.path.append(d)
            break
    import pybookreader

from pybookreader.config import bookmarks_file

#print dir(pybookreader)
locale.setlocale(locale.LC_ALL, '')
enc = locale.getlocale()[1]

db = shelve.open(bookmarks_file)
#print '======== db.keys ========'
#pprint(db.keys())
#print '========================='
print 'bookmarks_db_version:',
if db.has_key('bookmarks_db_version'):
    print db['bookmarks_db_version'],
else:
    print 'WARNING!!! db can\'t has bookmarks_db_version'
    sys.exit()
if db['bookmarks_db_version'] == '0.4.6':
    print 'WARNING!!! db has old bookmarks_db_version'
    sys.exit()
print '- OK'
print '-'*80
import pybookreader.bookmarks

db_all_books = []
for key in db.keys():
    if key[0] == '/':
        db_all_books.append(key)

print '--== database files: ==--'
pprint(db_all_books)
print '-'*80

categories_list = db['categories_list']
books_list = db['books_list']
titles_list = db['titles_list']

print '--== categories_list: ==--'
cat_all_books = []
for cat in categories_list:
    print unicode(cat, 'utf-8').encode(enc, 'replace')
    for book in categories_list[cat]:
        if book not in cat_all_books:
            cat_all_books.append(book)
        print '  ', book

print '-'*80
print '--== titles_list: ==--'
for b in titles_list:
    print b, ':'
    print '  ', unicode(titles_list[b], 'utf-8').encode('koi8-r', 'replace')
#pprint(titles_list)

print '-'*80
print '--== books_list: ==--'
for b in books_list:
    print b
#pprint(books_list)

print '-'*80
print 'Warnings:'
for book in cat_all_books:
    if not book in db_all_books:
        print 'WARNING!!! book: %s exists in categories_list but don\'t exists in db' % book

for book in db_all_books:
    if not book in cat_all_books:
        print 'WARNING!!! book: %s exists in db but don\'t exists in categories_list' % book

for book in db_all_books:
    if not titles_list.has_key(book):
        print 'WARNING!!! book: %s exists in db but don\'t exists in titles_list' % book

for book in db_all_books:
    if not book in books_list:
        print 'WARNING!!! book: %s exists in db but don\'t exists in books_list' % book

print '-'*80
print 'current book:', db['current_book']

print '-'*80
print 'total books in database: %d' % len(db_all_books)
print 'total books in categories: %d' % len(cat_all_books)
print '-'*80
