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

import sys
import config
#from recreatedb import recreatedb


def main():

    #recreatedb()

    config.parse_options()

    if config.run_dict_client:
        run_dict_client()
        sys.exit()

    config.parse_filetypes()

    if config.run_bookmarks_manager:
        run_bookmarks_manager()
        sys.exit()


    import os
    import gtk
    from gtk import gdk
    from mainwindow import PyBookReader
    br = PyBookReader()
    br.main_window.show()
    if config.opt_files:
        filename = os.path.abspath(config.opt_files[0])
        br.set_current_book(filename)
    else:
        br.set_current_book()
    gdk.threads_init()
    gtk.main()


##----------------------------------------------------------------------

def run_dict_client():

    import os
    import gtk
    from gtk import gdk
    from dictclient.pygtkdict import PyGtkDict

    from config import dictclient_rc_file

    # search glade file
    gf = 'pybookreader/dictclient/pygtkdict.glade'
    dictclient_glade_file = None
    for d in sys.path:
        f = os.path.join(d, gf)
        if os.path.exists(f):
            dictclient_glade_file = f
            break

    if dictclient_glade_file:
        dict_client = PyGtkDict(dictclient_glade_file, dictclient_rc_file)
        dict_client.window.connect('destroy', lambda w: gtk.main_quit())
        gdk.threads_init()
        gtk.main()
    else:
        sys.exit('Can\'t find glade file - exit')

##----------------------------------------------------------------------

def run_bookmarks_manager():

    from bookmarks import Bookmarks
    from bookmarkswindow import BookmarksWindow
    import gtk
    import os

    def bookmarks_manager_unrealize_cb(w, bookmarks_manager, properties, bookmarks):
        width, height = w.get_size()
        properties['bookmarks_manager_width'] = width
        properties['bookmarks_manager_height'] = height
        properties['bookmarks_manager_paned_position'] \
             = bookmarks_manager.paned.get_position()
        properties['bookmarks_manager_show_category'] \
             = bookmarks_manager.show_category
        properties['bookmarks_manager_hide_bookmarks'] \
             = int(bookmarks_manager.hide_bookmarks)
        properties['bookmarks_manager_hide_cover'] \
             = int(bookmarks_manager.hide_cover)
        bookmarks.save_bookmarks()
        save_config_file(properties)

    def load_file_cb(w, filename):
        if config.external_reader:
            os.system('%s "%s" &' % (config.external_reader, filename))

    bookmarks = Bookmarks()

    properties = read_config_file()
    #print properties

    if properties:
        BookmarksWindow.hide_bookmarks \
            = int(properties['bookmarks_manager_hide_bookmarks'])
        BookmarksWindow.hide_cover \
            = int(properties['bookmarks_manager_hide_cover'])
        BookmarksWindow.show_category \
            = properties['bookmarks_manager_show_category']

    m = BookmarksWindow(bookmarks)

    if properties:
        width = int(properties['bookmarks_manager_width'])
        height = int(properties['bookmarks_manager_height'])
        m.window.resize(width, height)
        pos = int(properties['bookmarks_manager_paned_position'])
        m.paned.set_position(pos)

    m.window.connect('destroy', lambda w: gtk.main_quit())
    m.window.connect('unrealize', bookmarks_manager_unrealize_cb, m, properties, bookmarks)
    m.connect('load-file', load_file_cb)

    m.window.show()

    gtk.main()

##----------------------------------------------------------------------

def read_config_file():

    try:
        fd = open(config.config_file)
    except:
        return {}

    properties = {}
    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
            properties[line[0:indx]] = line[indx+1:-1]

    return properties


def save_config_file(properties):
    from miscutils import OpenFileDialog

    properties['file_select_path'] = OpenFileDialog.file_select_path

    try:
        fd = open(config.config_file, 'w')
    except IOError, err:
        print >> sys.stderr, \
              "ERROR: can't open configuration file: %s: %s", \
              config.config_file, err[1]
        return

    print >> fd, '[pybookreader]'

    for key, value in properties.items():
        print >> fd, '%s=%s' % (key, value)

    #print >> fd, ''

    fd.close()
