#!/usr/bin/env python

from threading import Lock
from narval.lib import *

class BinaryStore:
    """ This class is intended to define a storage of binarys extracted from a
    web page, dictionary-like, and all the methods necessary for extraction,
    storage, referencing of those binarys"""

    def __init__(self, dico={}):
        self.dico = dico
        self.path = ""
        self.id = 1 # 0 ois reserved to tr.png img
        self.Id_Lock = Lock()

    def get_urls(self):
        return [ u for (u,v) in self.dico.values() ]

    def get_binaries(self):
        return [ v for (u,v) in self.dico.values() ]

    def set_id(self):
        """ bon la je m'amuse heinnn"""
        self.Id_Lock.acquire()
        self.id+=1
        self.Id_Lock.release()
        return str(self.id)

    def get_id_from_url(self, url):
        # to trash
        for key, val in self.dico:
            if url == val[0]:
                return key
        
    def get_binary_from_id(self, id):
        try:
            return self.dico[id][1]
        except KeyError:
            return None

    def get_binary_from_url(self, url):
        vals = self.dico.values()
        for (u,img) in vals:
            if u==url:
                return img

    def add_binary(self, url, data_binary=None):
        import urllib
#        f = urllib.urlopen(normalize_url(url)[0])
#        data_binary = f.read()
        self.dico[self.set_id()] = (url, data_binary)

    def load_binary_from_id(self, id):
        url = self.dico[id][0]
        f = urllib.urlopen(normalize_url(url)[0])
        if not self.dico[id][1]:
            data_binary = f.read()
        else:
            data_binary = self.dico[id][1]
        f.close()
        return data_binary

    def load_binary_from_url(self, url):
        f = urllib.urlopen(normalize_url(url)[0])
        if not self.dico[id][1]:
            data_binary = f.read()
        else:
            data_binary = self.dico[id][1]
        f.close()
        return data_binary
