#!/usr/bin/env python
# -*- mode: python; coding: koi8-r; -*-
import sys, os, locale, string, getopt

program_name = 'PyBookReader'
program_version = '0.5.0'

##----------------------------------------------------------------------
## configuration

config_dir = os.path.expanduser('~/.pybr')
config_file = os.path.expanduser('~/.pybr/config')
bookmarks_file = os.path.expanduser('~/.pybr/bookmarks')
filetypes_file = os.path.expanduser('~/.pybr/filetypes')
dictclient_rc_file =  os.path.expanduser('~/.pybr/dictclient.rc')
dictclient_history_file = os.path.expanduser('~/.pybr/dictclient_history')

charsets_list = ('koi8-r', 'cp1251', 'cp866', 'iso8859-5', 'utf-8')

default_description_length = 200
preview_length = 4000
default_encoding = locale.getlocale()[1]
if not default_encoding:
    default_encoding='iso8859-1'
default_category = 'Default'

# from getopt
run_bookmarks_manager = 0
external_reader = None
run_dict_client = 0
opt_files = None

##----------------------------------------------------------------------
## filetypes

from parsers import *

file_types = {

    'gzipped_plain_text' : (('.gz',),                  # suffixes
                            gzipped_plain_text_parser, # parser
                            None, None),          # external_command, encoding

    'html'               : (('.htm', '.html'),
                            html_parser,
                            None, None),

##     'lib_ru_parser'        : (('txt.html',),
##                             lib_ru_parser,
##                             None, None),

    'gzipped_html'       : (('.htm.gz', '.html.gz'),
                            gzipped_html_parser,
                            None, None),

##     'zip'                : (('.zip'),
##                             zip_parser,
##                             None, None),

    'fb2'                : (('.fb2',),
                            fb2_parser,
                            None, None),

    'ms_doc'             : (('.doc',),
                            plain_text_parser,
                            'catdoc', None),

    'pdf'                : (('.pdf',),
                            plain_text_parser,
                            'pdftotext -enc UTF-8 %s -', 'utf-8'),

    'plain_text'         : (('',),
                            plain_text_parser,
                            None, None),
    }


def parse_filetypes():
    if not os.path.exists(filetypes_file): return
    import parsers
    try:
        fd = open(filetypes_file)
    except IOError, err:
        print >> sys.stderr, 'ERROR: Can\'t open config file: %s: %s' \
              % (filetypes_file, err[1])
        return

    new_file_types = {}

    #from pprint import pprint
    #pprint(file_types)

    def print_error(ln, msg):
        print >> sys.stderr, \
              'ERROR in config file: %s: line %d: %s' \
              % (filetypes_file, ln, msg)

    line_num = 1
    for line in fd.readlines():

        # split line
        words_list = []
        word = ''
        i = 0
        while i < len(line):
            char = line[i]
            if char == '#':
                if word:
                    print_error(line_num, 'sintax error')
                    return
                break
            if char in string.whitespace:
                if word:
                    words_list.append(word)
                    word = ''
                i += 1
                continue
            if char in ['\'', '"']:
                if word:
                    print_error(line_num, 'sintax error')
                    return
                i += 1
                j = line[i:].find(char)
                if j < 0:
                    print_error(line_num, 'no match')
                    return
                else:
                    words_list.append(line[i:i+j])
                    i += j+1
                continue
            word += char
            i += 1

        # add new file type to temporary filetypes dict
        if words_list:
            if not 3 <= len(words_list) <= 5:
                print_error(line_num, 'number of fields')
                return
            else:
                name = words_list[0]
                suffixes = words_list[1].split() or ['']
                if hasattr(parsers, words_list[2]):
                    parser = getattr(parsers, words_list[2])
                else:
                    print_error(line_num ,
                                'unknown parser: "%s"' % words_list[2])
                    return

                if len(words_list) < 4:
                    command = None
                elif words_list[3] in ['None', '']:
                    command = None
                else:
                    command = words_list[3]
                    if command.find('%s') > 0:
                        try:
                            command % ''
                        except:
                            print_error(line_num ,
                                        'format error: "%s"' % words_list[3])
                            return

                if len(words_list) < 5:
                    encoding = None
                elif words_list[4] in ['None', '']:
                    encoding = None
                else:
                    encoding = words_list[4]

                new_file_types[name] = (suffixes, parser, command, encoding)

        line_num += 1

    #pprint(new_file_types)

    # update filetypes
    global file_types
    file_types.update(new_file_types)

##----------------------------------------------------------------------
## options

def parse_options():

    help = '''%s
Usage: %s [options] [file]
  -b  --bookmarks-file=file     specify bookmarks file
  -M  --bookmarks-manager       run Books Manager
  -D  --dict-client             run Dict Client
  -R  --reader=program          external reader (with -M)
  -h  --help                    display this help
      --version                 show program version and exit''' \
    % (program_name, sys.argv[0])
##  -c  --charset <charset>       specify default charset


    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'b:c:hDMR:',
                                      ['charset=', 'help',
                                       'bookmarks-file=',
                                       'bookmarks-manager', 'dict-client',
                                       'reader='])

    except getopt.GetoptError, err:
        sys.exit('%s: %s\ntry %s --help for more information\n'
                 % (program_name, err, sys.argv[0]))


    for i in optlist:

        if i[0] in ['--help', '-h']:
            print help
            sys.exit()

        elif i[0] == '--version':
            print '%s v. %s' % (program_name, program_version)
            sys.exit()

        elif i[0] in ['--charset', '-c']:
            pass

##             global default_encoding
##             default_encoding = i[1]
##             try:
##                 codecs.lookup(default_charset)
##             except LookupError, err:
##                 sys.stderr.write('%s: %s\n' % (prog_name, err))
##                 sys.exit(2)

        elif i[0] in ['--bookmarks-file', '-b']:
            global bookmarks_file
            bookmarks_file = i[1]

        elif i[0] in ['--bookmarks-manager', '-M']:
            global run_bookmarks_manager
            run_bookmarks_manager = 1

        elif i[0] in ['--dict-client', '-D']:
            global run_dict_client
            run_dict_client = 1

        elif i[0] in ['--reader', '-R']:
            global external_reader
            external_reader = i[1]

    if args:
        global opt_files
        opt_files = args
