Subversion Repositories basico

Rev

Rev 229 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: collections.py
# Author: Tomás Vírseda
# License: GPL v3
# Description: Collections service

import os
import json
import uuid

from basico.core.env import FILE
from basico.core.service import Service

HEADER = ['id', 'title']
COLLECTIONS_FILE = FILE['COLLECTIONS']


class Collections(Service):
    def initialize(self):
        '''
        Setup Collections Service
        '''

        self.get_services()
        self.clts = {}
        self.load()


    def get_services(self):
        self.gui = self.app.get_service("GUI")
        self.uif = self.app.get_service("UIF")
        self.cb = self.app.get_service('Callbacks')
        self.im = self.app.get_service('IM')


    def load(self):
        try:
            with open(COLLECTIONS_FILE, 'r') as ft:
                self.clts = json.load(ft)
                self.debug ("Loaded %d collections" % len(self.clts))
        except Exception as error:
            self.debug("Collections file not found. Creating a new one.")
            self.save()


    def save(self, collections={}):
        if len(collections) == 0:
            collections = self.clts
        with open(COLLECTIONS_FILE, 'w') as ft:
            json.dump(collections, ft)
            self.debug ("Saved %d collections" % (len(collections)))


    def get_all(self):
        return self.clts


    def get_collections_name(self):
        names = []
        for tid in self.clts:
            names.append(self.clts[tid])
        return names


    def get_collections_id(self):
        tids = []
        for tid in self.clts:
            tids.append(tid)
        return tids


    def create(self, entry):
        tid = str(uuid.uuid4())
        name = entry.get_text()

        if len(name) == 0:
            return

        tid_exists = tid in self.get_collections_id()
        name_exists = name in self.get_collections_name()

        if tid_exists:
            self.debug('Collision? :)')
            self.create(entry)
        else:
            if name_exists:
                return
            else:
                self.clts[tid] = name
                self.debug("Created collection: %s" % name)
                self.save()


    def delete(self, tid):
        try:
            name = self.get_name(tid)
            del(self.clts[tid])
            self.debug("Deleted Collection: %s" % name)
            self.save()
            return True
        except KeyError:
            self.debug("You can't delete a non existent collection...")
        except Exception as error:
            self.debug("Error deleting collection: %s" % error)
            self.debug(self.clts)
            raise


    def get_name(self, tid):
        return self.clts[tid]