#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Command-line utility: generate XML note files that can be posted to the
API to add a note to all the person records in a repo.  (We use the API
to do this rather than the import mechanism so that subscribers will get
notified; see the call to importer.import_records in api.Write.post.)

To use:

    REPO='2015-nepal-earthquake'
    /usr/bin/python tools/download_feed.py \
      --format=csv \
      --out=persons.csv \
      --min_entry_date=2010-10-01 \
      --key=$PF_KEY \
      https://www.google.org/personfinder/$REPO/feeds/person
    tools/notes_for_all_persons \
      google.org/personfinder $USER@google.com persons.csv \
      /tmp/nepal-notes 2015-nepal-earthquake '2015-05-12T06:50:00Z' \
      information_sought note_body.txt
    Password: <enter your ASP>

The result will be a series of files prefixed with /tmp/nepal-notes that you can
then post to the Person Finder API to write the notes to the datastore like this:

    # Each file contains 100 notes by default.
    for i in `seq 0 100 10200`; do
      echo $i
      curl -X POST -H 'Content-type: application/xml' --data-binary @/tmp/nepal-notes.${i}.xml \
           https://www.google.org/personfinder/2015-nepal-earthquake/api/write?key=$PF_KEY
    done

"""

from model import *
import atom
import datetime
import logging
import csv
import remote_api
import sys

logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)


def all_person_record_ids(persons_feed_file_name):
    """Generates all the record IDs of persons in the given persons feed CSV file."""
    with open(persons_feed_file_name) as f:
        reader = csv.DictReader(f)
        for row in reader:
            yield row['person_record_id']

def write_notes_for_all_persons(
        persons_feed_file_name, basename, date, status, text, batch_size=100):
    """Writes XML Atom feeds of notes, one for every person in the persons feed file."""
    note_dicts = []
    for person_record_id in all_person_record_ids(persons_feed_file_name):
        # Generate a note record ID that (a) can never collide with a future
        # generated note record ID and (b) is a function of the person record
        # ID to ensure that at most one note is created per person regardless
        # of how many times this function is executed.
        domain, id = person_record_id.split('/', 1)
        note_record_id = domain + '/note.batch-' + id
        note_dicts.append({
            'note_record_id': note_record_id,
            'person_record_id': person_record_id,
            'author_name': 'Google Person Finder',
            'source_date': date,
            'status': status,
            'text': text
        })
    for i in range(0, len(note_dicts), batch_size):
        filename = basename + '.' + str(i) + '.xml'
        with open(filename, 'w') as file:
            atom.ATOM_PFIF_1_4.write_note_feed(
                file,
                note_dicts[i:i + batch_size],
                url='',
                title='Notes generated by notes_for_all_persons.py',
                subtitle='',
                updated=datetime.datetime.utcnow()
            )
        logging.info('wrote ' + filename)

if __name__ == '__main__':
    remote_api.connect(sys.argv[1], sys.argv[2], None)
    text = None
    with open(sys.argv[7]) as f:
        text = f.read().decode('utf-8')
    write_notes_for_all_persons(
            sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], text)
