# -*- coding: utf-8 -*-
################################################################
#  Copyright notice
#
#  (c) 2011 Siegfried Schweizer <siegfried.schweizer@sbb.spk-berlin.de>
#  All rights reserved
#
#  This script is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  The GNU General Public License can be found at
#  http://www.gnu.org/copyleft/gpl.html.
#
#  This script is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  This copyright notice MUST APPEAR in all copies of the script!
################################################################

"""
This is a helper script for DLF's indexer. Will soon write some more here.
"""

import sys
import os

from urlparse import urlsplit
import re
import types

from webdav.Connection import AuthorizationError
from webdav.WebdavClient import CollectionStorer

from functools import wraps
from time import time
import datetime

class IndexerHelper:
	
	def __init__(self):
		self.indexMets()
	
	def timed(f):
		@wraps(f)
		def wrapper(*args, **kwds):
			start = time()
			result = f(*args, **kwds)
			elapsed = time() - start
			#print "%s took %d seconds to finish." % (f.__name__, elapsed)
			n = open('indexerhelper.log', 'a+')
			n.write("%s took %d seconds to finish.\n\n" % (f.__name__, elapsed))
			n.close()
			return result
		return wrapper
	
	@timed
	def indexMets(*args, **kwds):
		
		dispatcherPath = '/srv/www/htdocs/presentation/typo3/cli_dispatch.phpsh'
		pid = '136'
		solrCore = 'dlfCore0'
		username = 'siegfried'
		password = 'password'
		webdavUrl = 'http://10.100.20.27/webdav/mets'
		webdavUrlPass = 'http://%s:%s@10.100.20.27/webdav/mets' % (username, password)
		
		rex = re.compile('PPN[a-zA-Z0-9]+\.xml')
		
		n = open('indexerhelper.log', 'a+')
		now = datetime.datetime.now()
		n.write('Starting new indexer run at %s\n' % now.strftime("%Y-%m-%d %H:%M"))
		
		webdavConnection = CollectionStorer(webdavUrl, validateResourceNames=False)
		
		authFailures = 0
		while authFailures < 2:
			try:
				for resource, properties in webdavConnection.getCollectionContents():
					try:
						slashparts = resource.path.encode(sys.getfilesystemencoding()).split('/')
						filename = slashparts[len(slashparts) - 1]
						found = re.search(rex, filename)
						if found:
							n.write('Indexing file %s\n' % filename)
							p = os.popen('%s dlf index -pid %s -core %s -doc %s/%s' % (dispatcherPath, pid, solrCore, webdavUrlPass, filename))
							s = p.readline()
							p.close()
							if len(s) != 0:
								n.write('%s' % s)
					except UnicodeEncodeError:
						print("Cannot encode resource path or properties.")
				break # break out of the authorization failure counter
			except AuthorizationError, e:
				if username is None or password is None:
					username = raw_input("User Name:").strip()
					password = raw_input("Password:").strip()
				if e.authType == "Basic":
					webdavConnection.connection.addBasicAuthorization(username, password)
				elif e.authType == "Digest":
					info = parseDigestAuthInfo(e.authInfo)
					webdavConnection.connection.addDigestAuthorization(username, password, realm=info["realm"], qop=info["qop"], nonce=info["nonce"])
				else:
					raise
				authFailures += 1
		n.close()

IndexerHelper()

