#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-


# Glasnost
# By: Odile Bénassy <obenassy@entrouvert.com>
#     Romain Chantereau <rchantereau@entrouvert.com>
#     Nicolas Clapiès <nclapies@easter-eggs.org>
#     Pierre-Antoine Dejace <padejace@entrouvert.be>
#     Thierry Dulieu <tdulieu@easter-eggs.com>
#     Florent Monnier <monnier@codelutin.com>
#     Cédric Musso <cmusso@easter-eggs.org>
#     Frédéric Péters <fpeters@entrouvert.be>
#     Benjamin Poussin <poussin@codelutin.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#     Sébastien Régnier <regnier@codelutin.com>
#     Emmanuel Saracco <esaracco@easter-eggs.com>
#
# Copyright (C) 2000, 2001 Easter-eggs & Emmanuel Raviart
# Copyright (C) 2002 Odile Bénassy, Code Lutin, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Frédéric Péters, Benjamin Poussin, Emmanuel Raviart,
#     Emmanuel Saracco & Théridion
# Copyright (C) 2003 Odile Bénassy, Romain Chantereau, Nicolas Clapiès,
#     Code Lutin, Pierre-Antoine Dejace, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Florent Monnier, Cédric Musso, Ouvaton, Frédéric Péters,
#     Benjamin Poussin, Rodolphe Quiédeville, Emmanuel Raviart, Sébastien
#     Régnier, Emmanuel Saracco, Théridion & Vecam
#
# 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

__doc__ = """Glasnost Curses Interface"""

__version__ = '$Revision$'[11:-2]


import ConfigParser
import curses
import os
import sys
import traceback

import glasnost.common.applications as applications
from glasnost.common.cache import cache
import glasnost.common.context as context
import glasnost.common.tools_new as commonTools

from glasnost.proxy.tools import getProxyForServerRole

from glasnost.gcurses.Articles import ArticlesScreen
from glasnost.gcurses.Rubrics import RubricsScreen


keysLabel = {
        curses.KEY_UP:    'Flèche Haut',
        curses.KEY_DOWN:  'Flèche Bas',
        curses.KEY_LEFT:  'Flèche Gauche',
        curses.KEY_RIGHT: 'Flèche Droite',
        }


class Application(applications.Application):
    applicationName = 'GlasnostCurses'
    applicationRole = 'curses'

    def handleGetopt(self):
        if len(sys.argv) > 2:
            self.usage()
            return 1

        commandLineContext = context.get(_level = 'commandLine')
        
        if len(sys.argv) > 1:
            dispatcherId = sys.argv[1]
            # Ensure that dispatcherId has a valid syntax.
            dispatcherId = commonTools.extractDispatcherId(dispatcherId)
            commandLineContext.setVar('dispatcherId', dispatcherId)

        return None

    def initContextCommandLineOptions(self):
        applications.Application.initContextCommandLineOptions(self)

        commandLineContext = context.get(_level = 'commandLine')

        language = os.environ.get('LANG')
        if language:
            language = language.split('_')[0].split('@')[0]
        else:
            language = 'C'
        commandLineContext.setVar('readLanguages', [language])

    def initContextOriginalOptions(self):
        applications.Application.initContextOriginalOptions(self)

        originalContext = context.get(_level = 'original')

        originalContext.setVar('cache', cache)

    def loadRcOptions(self):
        applications.Application.loadRcOptions(self)

        rcContext = context.get(_level = 'rc')

        dispatcherId = context.getVar('dispatcherId')
        hostName = dispatcherId[11:]
        config = ConfigParser.ConfigParser()
        try:
            config.readfp(open('%s/.glasnostrc' % os.environ['HOME']))
        except IOError:
            print 'Pas de fichier ~/.glasnostrc'
            print """
Pour info, format du fichier:

[dispatcherId]
username = loginPourCeDispatcher
password = passwordPourCeDispatcher
"""
            sys.exit(1)
        try:
            username = config.get(hostName, 'username')
            password = config.get(hostName, 'password')
        except ConfigParser.NoSectionError:
            print 'Pas de section pour ce dispatcher dans le ~/.glasnostrc'
            sys.exit(1)
        authenticationProxy = getProxyForServerRole('authentication')
        userToken = authenticationProxy.getUserToken(
                'login/password', (username, password))
        rcContext.setVar('userToken', userToken)
        userId = authenticationProxy.getUserId()
        rcContext.setVar('userId', userId)

        user = getProxyForServerRole('people').getObjectByLogin(username)
        context.setVar('loggedUser', user)

    def main(self, stdscr):
        self.launch()

        context.push(
            _level = 'main',
            debug = 1,
            screens = None
            stdscr = stdscr,
            )
        height, width = stdscr.getmaxyx()
        curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
        curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_RED)

        context.setVar('screens', [ RubricsScreen(stdscr) ])

        while len(context.getVar('screens')):
            stdscr = context.getVar('stdscr')

            stdscr.addstr(
                    0, 0, 'glasnostCurses %saide:?' % (' ' * (width - 21)),
                    curses.color_pair(1) | curses.A_BOLD)
            stdscr.addstr(height - 2, 0, ' ' * width, curses.color_pair(1))
            sc = context.getVar('screens')[-1]
            sc.view(height, width)
            c = sc.waitKey()

            if c == '?':
                stdscr.addstr(1, 0, ' ' * width)
                i = 2
                for k, v in sc.keys.items():
                    if k in keysLabel.keys():
                        label = keysLabel[k]
                    else:
                        label = '%c' % k
                    label = label.ljust(20)
                    stdscr.addstr(i, 0, '  %s: %s' % (label, v[1].ljust(50)))
                    i += 1
                for i in range(i, height - 2):
                    stdscr.addstr(i, 0, ' ' * width)

                stdscr.addstr(height - 1, 0, ' ' * (width - 1))
                stdscr.getch()
                continue

            if c == 'g':
                stdscr.addstr(height - 1, 0, 'Aller à: '.ljust(width - 1))
                curses.echo()
                name = stdscr.getstr(height - 1, 9, 40)
                curses.noecho()
                if name == 'articles':
                    context.getVar('screens').append(ArticlesScreen(stdscr))
                elif name == 'rubrics':
                    context.getVar('screens').append(RubricsScreen(stdscr))
                continue

    def usage(self):
        print 'Usage: glasnostCurses.py [ dispatcherId ]'
        print '       example: glasnost://www.entrouvert.org'


if __name__=='__main__':
    application = Application()
    curses.wrapper(application.main)

