#!/bin/python

import os
import logging
import StringIO
import zipfile
import sys
from ConfigParser import ConfigParser

htmlName = 'ole-group-list.html'
bundleBaseUrl = 'http://schoolserver/Activities/'

class MalformedBundleException(Exception):
    pass

class BundleInfo:
    "a trivial activityInfo substracter. ripped some stuff from the sugar code"

    id = None
    version = None

    def __init__(self, path):
        self._path = path

        zip_file = zipfile.ZipFile(self._path)
        file_names = zip_file.namelist()
        if len(file_names) == 0:
            raise MalformedBundleException('Empty zip file')

        self._zip_root_dir = file_names[0].split('/')[0]

        zip_file = zipfile.ZipFile(self._path)
        path = os.path.join(self._zip_root_dir, "activity/activity.info")
        try:
            data = zip_file.read(path)
            info_file = StringIO.StringIO(data)
        except KeyError:
            logging.debug('%s not found.' % filename)
            zip_file.close()

        cp = ConfigParser()
        cp.readfp(info_file)

        section = 'Activity'

        if cp.has_option(section, 'bundle_id'):
            self.id = cp.get(section, 'bundle_id')
        elif cp.has_option(section, 'service_name'):
            self.id = cp.get(section, 'service_name')
        else:
            raise MalformedBundleException(
                'Activity bundle %s does not specify a bundle id' %
                self._path)

        if cp.has_option(section, 'activity_version'):
            aVersion = cp.get(section, 'activity_version')
            try:
                self.version = int(aVersion)
            except ValueError:
                raise MalformedBundleException(
                    'Activity bundle %s has invalid version number %s' %
                    (self._path, aVersion))

try:
    sys.argv[1]
except IndexError:
    print "need to supply bundle dir as first and only argument"
    sys.exit(2)

header = """
<html>
  <head>
  </head>

  <body>
The following activities are the ones used when updating activities on schoolserver from xo's:
<br/>
<br/>
"""

footer = """
  </body>
</html>
"""

def makeItemString(actId, actVer, actUrl, actName):
    return """
      <br/>
      <span class="olpc-activity-info">
          <span class="olpc-activity-id" style="display:none;">%s</span>
          <span class="olpc-activity-version" style="display:none;">%s</span>
          <span class="olpc-activity-url"><a href='%s'>%s</a></span>
      </span>
    """ % (actId, actVer, actUrl, actName)


FILE = open(htmlName, "w")

bundlePath = sys.argv[1]
bundles = os.listdir(bundlePath)

FILE.write(header)

for bundName in bundles:
    if  bundName.split(".")[-1] == "xo":
        bund = BundleInfo(bundlePath + '/' + bundName)
        FILE.write(makeItemString(bund.id,
                                  bund.version,
                                  bundleBaseUrl + bundName,
                                  bundName)
                   + '\n')

FILE.write(footer)
FILE.close()
