from elixir              import Unicode, DateTime, String, Integer, Field
from elixir              import ManyToOne, OneToMany, ManyToMany
from elixir              import Entity, using_options
from datetime            import datetime
from sqlalchemy          import *
from turbogears.database import metadata, session

class Program(Entity):
    name        = Field(String(20), primary_key=True)
    events      = OneToMany('Event', inverse='program')
    hosts       = ManyToMany('Host', inverse='programs')

class Host(Entity):
    name        = Field(String(50), primary_key=True)
    events      = OneToMany('Event', inverse='host')
    programs    = ManyToMany('Program', inverse='hosts')

class Event(Entity):
    data        = Field(String(255))
    timestamp   = Field(DateTime())
    program     = ManyToOne('Program', inverse='events')
    host        = ManyToOne('Host', inverse='events')

    @staticmethod
    def new(timestamp, host, program, data):
        h = Host.get_by(name=host)
        if not h:
            h = Host(name=host)
            session.flush()
        p = Program.get_by(name=program)
        if not p:
            p = Program(name=program)
            session.flush()
        h.programs.append(p)
        e = Event(timestamp=timestamp, host=h, program=p, data=data)
        return e