#!/usr/bin/python
# Copyright (C) 2009, Sugar Labs
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

import logging
from HTMLParser import HTMLParser

import gio

from jarabe import config

#_UPDATE_PATH = 'http://activities.sugarlabs.org/services/update-aslo.php'
_UPDATE_PATH = 'http://wiki.paraguayeduca.org/index.php/Actividades_y_contenidos'

_fetcher = None
# flag indicating whether we've parsed the url once or not
_activity_list_populated = False

_ACTIVITIES_LIST = {}

class _UpdateFetcher(HTMLParser):

    def __init__(self, bundle, completion_cb):
        # ASLO knows only about stable SP releases
        major, minor = config.version.split('.')[0:2]
        sp_version = '%s.%s' % (major, int(minor) + int(minor) % 2)
        # Reset the HTMLParser.
        # FIXME: Check why it does not get reset on its own.
        self.reset()
        self._activity_id = ''
        self._activity_url = ''
        self._activity_version = ''
        self._inside_activity_version = False
        self._inside_activity_id = False
        self._inside_activity_url = False

        url = _UPDATE_PATH

        self._completion_cb = completion_cb
        self._file = gio.File(url)
        self._bundle = bundle
        logging.debug('Fetch %s', url)
        self._file.load_contents_async(self.__download_file_complete_cb)

    def __download_file_complete_cb(self, gdaemonfile, result):
        content = self._file.load_contents_finish(result)[0]
        self.feed(content)

    def handle_endtag(self, tag):
        if tag == 'body':
            self._completion_cb(None, None, None, None, None)

    def handle_starttag(self, tag, attrs):
        if tag == 'span':
            for attribute,value in attrs:
                if value == 'olpc-activity-id':
                    self._inside_activity_id = True
                elif value == 'olpc-activity-version':
                    self._inside_activity_version = True
                elif value == 'olpc-activity-url':
                    self._inside_activity_url = True

        elif tag == 'a':
            if self._inside_activity_url:
                for attribute,value in attrs:
                    if attribute == 'href':
                        self._activity_url = value
                        self._inside_activity_url = False

    def handle_data(self, data):
        if self._inside_activity_version:
            self._activity_version = data
            self._inside_activity_version = False
            _ACTIVITIES_LIST[self._activity_id] = \
                    {'version':self._activity_version,
                            'url':self._activity_url,
                            'size':0}
            global _activity_list_populated
            _activity_list_populated = True
            if self._bundle._bundle_id == self._activity_id:
                self._completion_cb(self._bundle, self._activity_version,
                        self._activity_url, 0, None)
        elif self._inside_activity_id:
            self._activity_id = data
            self._inside_activity_id = False

def fetch_update_info(bundle, completion_cb):
    '''Queries the server for a newer version of the ActivityBundle.

       completion_cb receives bundle, version, link, size and possibly an error
       message:

       def completion_cb(bundle, version, link, size, error_message):
    '''
    global _fetcher

    if bundle._bundle_id in _ACTIVITIES_LIST:
        _fetcher = None
        completion_cb(bundle,
                _ACTIVITIES_LIST[bundle._bundle_id]['version'],
                _ACTIVITIES_LIST[bundle._bundle_id]['url'],
                _ACTIVITIES_LIST[bundle._bundle_id]['size'], None)
        return

    global _activity_list_populated
    if _activity_list_populated == True:
        completion_cb(bundle, None, None, None, None)
    else:
        if _fetcher is not None:
            raise RuntimeError('Multiple simultaneous requests are not supported')

        _fetcher = _UpdateFetcher(bundle, completion_cb)
