"""Resource, URI, and namespace tools
"""
from __future__ import generators
import sys

warnings = "--warn-undefined" in sys.argv
uriref = str


def resource(uri, fragment=""):
    return uri + fragment


def local(res):
    uri = uriref(res)
    end = uri.find('#')
    if end == -1:
        return ""
    else:
        return uri[end + 1:]


class Namespace:
    def __init__(self, uri, *shorts):
        self._uri = uri
        reg = self.__dict__
        for short in shorts:
            reg[short] = resource(uri, short)

    def __iter__(self):
        attrs = self.__dict__
        for attr in attrs:
            if not attr.startswith('_'):
                yield attrs[attr]

    def __call__(self, short):
        return resource(self._uri, short)

    def __str__(self):
        return self._uri

    def __getattr__(self, name):
        if name.startswith('_'):
            raise AttributeError(name)
        result = self.__dict__[name] = resource(self._uri, name)
        if warnings:
            print "Warning: undefined identifier:", result
        return result


def makeseq(pattern="genid:#_%.3d", number=1):
    def generate(pattern, number):
        while True:
            yield resource(pattern % number)
            number += 1
    return generate(pattern, number).next

genid = makeseq()
rdf = Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "type")
rdfs = Namespace("http://www.w3.org/2000/01/rdf-schema#", "isDefinedBy",
                 "seeAlso", "Class", "subClassOf")
anon = Namespace(
    "#",
    "Address",
    "AlarmHi",
    "AlarmHiHi",
    "AlarmLo",
    "AlarmLoLo",
    "Alias",
    "Alternative_Name",
    "Channel",
    "Class",
    "ControlIndex1",
    "ControlIndex2",
    "ControlInvert",
    "ControlObjectType1",
    "ControlObjectVariation1",
    "ControlObjectType2",
    "ControlObjectVariation2",
    "ControlOnly",
    "CountMax",
    "CountMin",
    "DataGroup",
    "DefaultState",
    "DeviceClass",
    "DeviceType",
    "Enmac_Name",
    "Enmac_Number",
    "EventObjectType",
    "EventObjectVariation",
    "GroupAlias",
    "Index",
    "IsDouble",
    "Location_Name",
    "Name",
    "ObjectType",
    "ObjectVariation",
    "PREFIX",
    "Plant_Type",
    "Point",
    "REGION",
    "RangeMax",
    "RangeMin",
    "SUBSTATION",
    "UnknownID",
    "UnknownZone",
    "VOLTAGE_RATING",
    "Zone",
    "AnaPt",
    "DigPt",
    "TelePt",
    "Rtu",
    "Plant",
    "code",
    "description",
    "display",
    "group",
    "mosaic",
    "name",
    "pid",
    "rtu",
    "symbol",
    "type",
    "value",
    "world",
    "x",
    "y",
)


def test01():
    n = Namespace("#")
    assert str(n) == "#"


def test02():
    r = resource("#")
    assert uriref(r) == "#"


def test03():
    r = resource("test:x#", "jake")
    assert uriref(r) == "test:x#jake"


def test04():
    r = resource("test:x#jake")
    assert uriref(r) == "test:x#jake"

# def test05():
#       r = resource("test:x#jake")
#       assert r.uri == "test:x#"


def test06():
    r = resource("test:x#jake")
    assert local(r) == "jake"


def test07():
    r = resource("test:x#jake")
    s = resource("test:x#", "jake")
    assert r == s


def test08():
    n = Namespace("test:x#", "a", "b", "c")
    assert uriref(n.a) == "test:x#a"
    assert uriref(n.b) == "test:x#b"


def test09():
    n = Namespace("test:x#", "a", "b", "c")
    assert uriref(n("jake")) == "test:x#jake"
    assert uriref(n("b")) == "test:x#b"

# def test10():
#       n = Namespace("test:x#", "a", "b", "c")
#       try:
#               n.jake
#       except AttributeError:
#               pass
#       else:
#               assert 0


def test11():
    n = Namespace("test:x#", "jake")
    for r in n:
        assert uriref(r) == "test:x#jake"
        break
    else:
        assert 0

if __name__ == "__main__":
    from testrunner import run
    run(globals())
