#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-

from scriptingTools import *
from glasnost.proxy.tools import getProxyForServerRole
from glasnost.common.cache import cache

context.setVar('cache', cache)

dispatcherId = sys.argv[1]

init(dispatcherId)

print 'Getting articles'
articlesProxy = getProxyForServerRole('articles')
articles = articlesProxy.getObjects()

d = {}
for id in articles.keys():
    d[id] = 0

print 'Getting rubrics'
rubricsProxy = getProxyForServerRole('rubrics')
rubrics = rubricsProxy.getObjects()

print 'Getting pagenames'
pagenamesProxy = getProxyForServerRole('pagenames')
pagenames = pagenamesProxy.getObjects()

pagenamesD = {}
for p in pagenames.values():
    pagenamesD[p.name] = p.mappedId
pagenames = pagenamesD

print 'Marking articles that are part of rubrics'
for r in rubrics.values():
    if r.contentId:
        d[r.contentId] = 1
    if not r.membersSet:
        continue
    for id in r.membersSet:
        d[id] = 1

print 'Parsing every articles for links'
import re
for article in articles.values():
    if article.format == 'spip':
        links = [x[10:].strip() for x in re.findall(r'->article +\d+', article.body)]
        for l in links:
            id = '%s/articles/%s' % (dispatcherId, l)
            d[id] = 1
        links = [x[8:].strip() for x in re.findall(r'->alias +[\w\-_]+', article.body)]
        for l in links:
            if not pagenames.has_key(l):
                print 'Wrong pagename: %s' % l
                continue
            d[pagenames[l]] = 1
    elif article.format == 'rst':
        links = [x[10:].strip() for x in re.findall(r'<article +\d+', article.body)]
        for l in links:
            id = '%s/articles/%s' % (dispatcherId, l)
            d[id] = 1
        links = [x[8:].strip() for x in re.findall(r'<alias +[\w\-_]+', article.body)]
        for l in links:
            if not pagenames.has_key(l):
                print 'Wrong pagename: %s' % l
                continue
            d[pagenames[l]] = 1
        

print 'Results'

for id in d.keys():
    if d[id]:
        continue
    print '%3s: %s' % (commonTools.extractLocalId(id), articles[id].getLabel())


