import requests
import json
import hashlib

class ChoositRegisterWS(object):
    def __init__(self, url, key):
        self.url = url
        self.key = key

    def categories(self):
        return requests.post(self.url, data={'action': 'read'}).json()

    def create(self, newsletter, email):
        return requests.post(self.url, data={'action': 'create', 'email': email,
                'newsletter': newsletter, 'hash': hashlib.sha1(self.key+email).hexdigest()
            }).json()

    def delete(self, newsletter, email):
        return requests.post(self.url, data={'action': 'delete', 'email': email,
                'newsletter': newsletter, 'hash': hashlib.sha1(self.key+email).hexdigest()
            }).json()

    def update(self, subscriptions, email):
        '''Returns { 'email': 'bdauvergne@entrouvert.com',
                     'hash': 'ab60e5e1b226561092c082ca73a2ad9ee4527c7b',
                     'status': 'ok'}
           or

             { 'email': 'bdauvergne@entrouvert.com',
               'hash': 'ab60e5dgd34543543',
               'status': 'nok',
               'error': 'error message'}
        '''
        if isinstance(subscriptions, basestring):
            subscriptions = subscriptions.split(',')
        params = {
                'action': 'update', 
                'email': email,
                'hash': hashlib.sha1(self.key+email).hexdigest()
            }
        for i, subscription in enumerate(subscriptions):
            params['subscriptions[%d]'% i] = subscription
        res = requests.post(self.url, data=params)
        print res.request.body
        return res.json()

    def subscriptions(self, email):
        '''Returns { 'email': 'johndoe@example.com',
                     'hash': 'ef787...',
                     'newsletters': { '1': 'newsletter 1', ... },
                     'subscriptions': [ '1' ] }
        '''
        return requests.post(self.url, data={'action': 'read', 'email': email,
            'hash': hashlib.sha1(self.key+email).hexdigest()}).json()

    def newsletters(self, categories):
        params = {'action': 'read_newsletters'}
        for i, categorie in enumerate(categories):
            params['categories[%d]' % i] = categorie
        return requests.post(self.url, data=params).json()

if __name__ == '__main__':
    import sys
    # ne fonctionne que depuis lantana
    # examples: 
    # python choosit.py 'https://emailingeco.montpellier-agglo.com/ws/index.php' mykey subscriptions 'bdauvergne@entrouvert.com'
    # python choosit.py 'https://emailingeco.montpellier-agglo.com/ws/index.php' mykey update '315,316' 'bdauvergne@entrouvert.com'

    ws = ChoositRegisterWS(sys.argv[1], sys.argv[2])
    func = getattr(ws, sys.argv[3])
    import pprint
    pprint.pprint(func(*sys.argv[4:]))
