#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright © 2013 Luke Faraone, all rights reserved

from urllib2 import urlopen
from xml.dom.minidom import parseString
import datetime
import time

def initiateOutboundCall(number, nextNumber):
    log(99994)
    call(number)
    log(99995)
    response = ask("O T R S. I believe you requested to initiate a call to %s. Press any key to continue." % " ".join(list(nextNumber)),
            {'voice': 'vanessa',
             'attempts':3,
             'mode': 'dtmf',
             'choices': '[1 DIGIT]',
             'onChoice': lambda event: continueCall(nextNumber),
             'onBadChoice': lambda event: say("Sorry, didn't catch that. Press any key to confirm."),
             })
    log(99996)


def continueCall(number):
    say("Connecting you now.", {'voice': 'vanessa'})
    transfer(number, {'callerId': "4155230563",
                      'answerOnMedia': True})

def main(takeAction):
    log(99992)
    if takeAction is not None:
        log(99993)
        return initiateOutboundCall(callMe, thenCall)
    lecture_s = "<speak> This is a number used by volunteer response team members with the Wikimedia Foundation. Specific agents cannot be contacted at this number. If you require a response, please email <break time='200ms'/>in-fo<break time='200ms'/> dash <break time='100ms'/> e<break time='50ms'/> ehn <break time='100ms'/> at wikimedia <break time='100ms'/> dot org</speak>"
    wait(100)
    response = ask(lecture_s, {'voice': 'vanessa', 'choices': '[4 DIGITS]'})

    if response.value == 7472:
        say("Welcome O T R S Agent!")
        key = ask("What is your access code?", {'voice': 'vanessa', 'choices', '[10 DIGITS]'})
        from urllib2 import urlopen
        if urlopen("https://lfaraone.scripts.mit.edu/validate.cgi?%i" % key).getcode() == 200:
            num = ask("Stellar. Who would you like to call?", {'choices', '[10 DIGITS]'})
            continueCall(num)
        else:
            say("Your access code was rejected by the remote.")

    else:
        say("Sorry, that operation is not supported at this time.")
log(99991)
try:
    main(callMe)
    log(99)
except NameError:
    main(None)
