

# FIXME use Oauth instead of Basic authentication:
# https://mailchimp.com/developer/guides/how-to-use-oauth2/

from datetime import datetime, timedelta
import pytz  # Though only needed if we want a daylight savings-aware, non-GMT timezone, and it's a fussy package, it's needed in various Django modules, so might as well use it.
from django.utils import timezone
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.contrib.auth.models import User
from mailchimp3 import MailChimp
import requests
#import pdb
#import pprint

   


# Mailchimp API code taken from https://blog.theodo.com/2018/01/monkey-see-django-mailchimp-automation-django/
# and https://github.com/VingtCinq/python-mailchimp

class Command(BaseCommand):
  help = "Uploading emails and names of new customers to a mailing list on Mailchimp.com."

  def handle(self, *args, **options):
    try:
      # Get new customers
      # NOTE: Be sure this time zone matches what the database is set to, and that the database matches what the OS is set to.
      self.cutoffTime = (datetime.now(timezone.utc) - timedelta(seconds=int(settings.MAILLIST_NEW_CUSTOMER_CHECK_INTERVAL_SECONDS)))
      newCustomers = User.objects.filter(date_joined__gt = self.cutoffTime)
      members = []
      if not newCustomers:
        pass
        #self.stdout.write("No new customers for mailing list.")
      else:
        # prepare to contact Mailchimp
        headers = requests.utils.default_headers()
        headers['User-Agent'] = 'ron.newman@gmail.com'
        client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, mc_user=settings.MAILCHIMP_SITE_ADMIN_USERNAME, timeout=20.0, request_headers=headers)

        # select which list on Mailchimp to add to
        mailingLists = client.lists.all(get_all=True, fields="lists.name,lists.id")
        listId = [item["id"] for item in mailingLists["lists"] if item["name"]==settings.MAILCHIMP_LIST_NAME][0]

        for cust in newCustomers:
          # for batching (which haven't been able to get working using Mailchimp3)
          #members.append(customer_to_mailchimp_member(cust.email, cust.first_name, cust.last_name))
          #batchInfo = batch_add_members_to_list(client, members, listId)
          # see results
          #status = client.batches.get(batchInfo["id"])

          # Subscribe new member to the list.
          self.stdout.write("Adding a customer to mailing list who signed up after " + str(self.cutoffTime.strftime('%Y-%m-%d %H:%M:%S%z')) + " UTC (Time interval: " + str(int(settings.MAILLIST_NEW_CUSTOMER_CHECK_INTERVAL_SECONDS) / 60) + " minutes.)")
          newmember = {
            'email_address': cust.email.lower(),
            'status': 'subscribed',
            'merge_fields': {
              'FNAME': cust.first_name,
              'LNAME': cust.last_name,
            }
          }
          # FIXME: does client...create return some kind of status that can be echoed?
          client.lists.members.create(listId, newmember)
          self.stdout.write("Successfully added: " + str(newmember) )
          self.stdout.write("\n\n")

    except CommandError as err:
      self.stdout.write(str(err))
      self.stdout.write("\n\n")
    except Exception as err:
      self.stdout.write(str(err))
      self.stdout.write("\n\n")



"""
def customer_to_mailchimp_member(email,first_name,last_name):
  return {
    'status': 'subscribed',
    'email_address': email,
    'merge_fields': {
      'FNAME': first_name,
      'LNAME': last_name,
    }
  }
"""

"""
def batch_add_members_to_list(client, members, list_id):
  operations = [{
    'method': 'POST',
    'path': '/lists/' + list_id + '/members',
    'path': "/campaigns", # The relative path of the operation
    'body': json.dumps(member), # The JSON payload for PUT, POST, or PATCH
    'operation_id': str(operation_id), # A string you provide that identifies the operation
    'params': {...}, Any URL params, only used for GET
  } for member in members]
"""


