# -*- coding: utf-8 -*-
# Copyright 2008-2009, Felspar Co Ltd. http://fost.3.felspar.com/
# Distributed under the Boost Software License, Version 1.0.
# See accompanying file LICENSE_1_0.txt or copy at
#     http://www.boost.org/LICENSE_1_0.txt


def name_from_django_user(u):
    return "%s %s <%s>" % (u.first_name, u.last_name, u.email)

def flags_from_django_user(u):
    return ['active' if u.is_active else 'unactive']

def build_user_request(users, address_fn = name_from_django_user, flags_fn = flags_from_django_user, areas=None, unsubscribe=None):
    request = []
    for user in users:
        json = {
            'address': address_fn(user),
            'flags': flags_fn(user)
        }
        if areas:
            json['areas'] = areas
        if unsubscribe:
            json['unsubscribe'] = unsubscribe
        request.append(json)
    return request


def subscribe(host, api_key, api_secret, area, users):
    from appservices import agent
    ua = agent(api_key, api_secret, host)
    relurl = '/subscribe/%s' % area
    response, json = ua.post(relurl, users)
    return ua.base_url(relurl), users, response, json
