#!/bin/env python2.4
import logging
import os

debug = logging.getLogger("fm").debug
error = logging.getLogger("fm").error

from constants import FM_PROJECTS_FILENAME
from fmcomm import FMComm
from FMProjectVO import FMProjectVO
from messageQueue import mainMessageQueue

try:
    set = set
except:
    from sets import Set
    set = Set

NO_CONNECT_DEBUG = 0

class FM:
    def __init__(self, data_path, fm_comm=None, username=None, password=None):
        self.projects_path = os.path.join(data_path, FM_PROJECTS_FILENAME)
        self.projects = None
        self.fm_comm = fm_comm or FMComm(data_path)
        if username and password:
            self.initialize(username, password)


    def initialize(self, username, password):
        debug("Initializing")
        # retrieve the saved projects, if any
        projects = self.load_projects()

        self.fm_comm.set_credentials(username, password)
        # get the current projects on freshmeat
        if NO_CONNECT_DEBUG: fm_projects = projects
        else: fm_projects = self.fm_comm.get_projects()

        debug("fm_projects: %s", str(fm_projects))
        debug(" ")
        debug("projects: %s", str(projects))
        
        # get the projects that are not saved
        missing_projects = fm_projects - projects

        # for each of the missing_projects get the
        # packages then add it to the project set
        for project in missing_projects:
            projects.add(project)

        self.projects = projects
        if missing_projects:
            self.save_projects()
        return self.projects


    def get_projects(self):
        return self.projects

    def __get_saved_dict(self, parts):
        d = {}
        for p in parts:
            key, val = p.split("=")
            key = key.strip()
            val = val.strip().replace('"', '')
            d[key] = val
        return d


    def load_projects(self):
        debug("Loading projects from %s" % self.projects_path)
        projects = set()
    
        try:
            fp = open(self.projects_path, "r")
            project = None
            for line in fp:
                parts = line.strip().split(":")
                if parts[0] == 'PROJECT':
                    pdict = self.__get_saved_dict(parts[1:])
                    project = FMProjectVO(pdict['projectname'],
                                          pdict['shortname'],
                                          pdict['groupid'],
                                          pdict['sf_projectname'])
                    packages = set()
                elif parts[0] == '/PROJECT':
                    projects.add(project)                    
            fp.close()
        except Exception, e:
            error(e)
        debug("Loaded %d projects", len(projects))
        return projects


    def save_projects(self, projects=None):
        debug("Saving projects to %s", self.projects_path)
        if not projects: projects = self.projects

        try:
            fp = open(self.projects_path, "w")
            for project in projects:
                fp.write('PROJECT: projectname="%s": shortname="%s": groupid="%s": sf_projectname="%s"\n' % (project.getProjectName(), project.getShortName(), project.getGroupId(), project.getSFProjectName()))
                fp.write("/PROJECT\n")
            fp.close()
        except Exception, e:
            error(e)
            return




if __name__ == '__main__':
    pass


