#!/usr/bin/env python
# coding:utf-8

#import logging
import requests
#from cplLdaplib import Ldap


msg0100 = 'fetching configuration for: \'{0}\''
msg0101 = 'performing email white list upload'
msg0102 = 'found {0} email addresses'
msg0103 = 'failed to upload whitelist\n{0}'
msg0104 = 'whitelist successfully uploaded\n{0}'


class WhileListUpload():

	def __getWLUConfig(self):

		cfg_def = {
			'interfaceurl' : '',
			'interfacepassword' : '',
			}
		cfg_ver = {
			'interfaceurl' : ('str', ),
			'interfacepassword' : ('str', ),
			}

		# get white list upload configuration
		self.logger.debug(msg0100.format('WhileListUpload'))
		self.config.updateDefaults('WhileListUpload', cfg_def)
		self.config.updateVerify(cfg_ver)

		return self.config.getSection('WhileListUpload')


	def whitelistUpload(self):

		wlu_config = self.__getWLUConfig()

		if not wlu_config['interfaceurl'] or \
			not wlu_config['interfacepassword']: return

		self.logger.debug(msg0101)

		# search all email addresses in ldap
		gosa_ldap_cfg = self.config.getSection('GosaLdap')
		search_dn = gosa_ldap_cfg['searchbase']
		search_s = 'sub'
		search_f = '(objectClass=gosaMailAccount)'
		search_a = (
			'objectClass',
			'mail',
			'gosaMailAlternateAddress',
			)

		search_r = self.gosa_ldap.searchLdap(
			search_dn, search_s, search_f, search_a)

		# compile a list of all email adresses
		mail_addr_list = []

		for dn, attrs in search_r:

			if 'gosaUserTemplate' in attrs['objectClass']:
				continue

			if attrs.has_key('mail'):
				for mail_addr in attrs['mail']:
					mail_addr_list.append(mail_addr)

			if attrs.has_key('gosaMailAlternateAddress'):
				for mail_addr in attrs['gosaMailAlternateAddress']:
					mail_addr_list.append(mail_addr)

		self.logger.debug(msg0102.format(len(mail_addr_list)))

		#headers = {
		#	'content-type' : 'multipart/form-data',
		#}

		payload = {
			'emailliste' : ('nofile', "\n".join(mail_addr_list), 'text/plain'),
			'password' : (None, wlu_config['interfacepassword'], 'form-data'),
			'meldungen' : (None, 'voll', 'form-data'),
		}

		# params=params,
		# headers=headers,
		response = requests.post(wlu_config['interfaceurl'], files=payload)

		if response.status_code != 200:
			self.logger.error(msg0103.format(response.text))
		else:
			self.logger.info(msg0104.format(response.text))

