#!/usr/bin/env python

import sys
import time
import requests
import xml.etree.ElementTree

API_HOST = 'api.evpsys.com'
API_TOKEN = '{PUT-YOUR-TOKEN-HERE}'
API_KEY = '{PUT-YOUR-KEY-HERE}'


def get_document(text):
    document = xml.etree.ElementTree.fromstring(response.text)
    if document.find('status').text not in ['ok', 'pending']:
        raise Exception(document.find('error-text').text)
    return document


# Build the auth
auth = (API_TOKEN, API_KEY)

# Create the portfolio -------------------------------------------------------
portfolio = """
    <input version="1.0">
     <portfolio death-date="20180303" distribution-date="20180403" appraisal-date="20180404" name="John Doe" account="Account #123"
       title-1="Estate of John Doe">
      <lot number="1" identifier="IBM" shares="123.456" />
      <lot number="2" identifier="MSFT" shares="789" />
      <lot number="4" identifier="AMZN" shares="9876.54321" />
     </portfolio>
    </input>
"""
print('Creating the portfolio...')
try:
    response = requests.post('https://%s/portfolio?output=xml' % (API_HOST), auth=auth, data=portfolio)
    response.raise_for_status()
except Exception as e:
    print('  FAILED (POST /portfolio error: %s)' % repr(e))
    sys.exit(-1)
print('  Succeeded')

# Get the portfolio-id from the response -------------------------------------
print('Getting the portfolio-id...')
try:
    document = get_document(response.text)
    portfolio_id = document.find('portfolio-id').text
except Exception as e:
    print('  FAILED (POST /portfolio response format error: %s)' % repr(e))
    sys.exit(-1)
print('  Succeeded')

# Add and modify lots in the portfolio, using the portfolio-id ---------------
print('Updating lots in portfolio...')
portfolio = """
    <input version="1.0">
     <portfolio>
      <lot number="3" identifier="AAPL" shares="123">
       <alt shares="0">
        <action type="Sold" date="20180601" shares="100" />
        <action type="Sold" date="20180602" shares="20" />
        <action type="Sold" date="20180701" identifier="TSLA" shares="321" />
       </alt>
      </lot>
      <lot number="4" identifier="AMZN" shares="1234.5678" />
     </portfolio>
    </input>
"""
try:
    response = requests.put('https://%s/portfolio/%s?output=xml' % (API_HOST, portfolio_id), auth=auth, data=portfolio)
    response.raise_for_status()
except Exception as e:
    print('  FAILED (PUT /portfolio/{portfolio-id} error: %s)' % repr(e))
    sys.exit(-1)
try:
    document = get_document(response.text)
except Exception as e:
    print('  FAILED (PUT /portfolio/{portfolio-id} response format error: %s)' % repr(e))
    sys.exit(-1)
print('  Succeeded')

# List the existing portfolios -----------------------------------------------
print('Listing the portfolios...')
try:
    response = requests.get('https://%s/portfolio?output=xml' % (API_HOST), auth=auth, data=portfolio)
    response.raise_for_status()
    document = get_document(response.text)
    for portfolio in document.iter('portfolio'):
        print('  Portfolio: %s (ID %s, created %s)' % (portfolio.attrib.get('name', '[Unknown]'), portfolio.attrib['id'],
              portfolio.attrib['portfolio_time_created']))
    if document.find('more').text == 'true':
        print('  ...and more')
except Exception as e:
    print('  FAILED (GET /portfolio error: %s)' % repr(e))
    sys.exit(-1)
print('  Succeeded')

# Start an evaluation of the portfolio, using the portfolio-id ---------------
print('Starting the report...')
try:
    response = requests.post('https://%s/portfolio/%s/estateval/report?output=xml&report=dod' % (API_HOST, portfolio_id), auth=auth)
    response.raise_for_status()
except Exception as e:
    print('  FAILED (POST /portfolio/{portfolio-id}/estateval/report error: %s)' % repr(e))
    sys.exit(-1)
print('  Succeeded')

# Get the report-id from the response ----------------------------------------
print('Getting the report-id...')
try:
    document = get_document(response.text)
    report_id = document.find('report-id').text
except Exception as e:
    print('  FAILED (POST /portfolio/{portfolio-id}/estateval/report response format error: %s)' % repr(e))
    sys.exit(-1)
print('  Succeeded')

# Poll the report-id for completion ------------------------------------------
print('Polling the report status...')
try:
    while True:
        response = requests.get('https://%s/portfolio/%s/estateval/report/%s/status?output=xml' % (API_HOST, portfolio_id, report_id), auth=auth)
        response.raise_for_status()
        document = get_document(response.text)
        if document.find('status').text == 'ok':
            break
        print('  %03d%%: %s' % (int(document.find('pending-percent').text), document.find('pending-text').text))
        time.sleep(1)
except Exception as e:
    print('  FAILED (GET /portfolio/{portfolio-id}/estateval/report/{report-id}/status error: %s)' % repr(e))
    sys.exit(-1)
print('  Succeeded')

# List the existing reports --------------------------------------------------
print('Listing the reports...')
try:
    response = requests.get('https://%s/portfolio/%s/estateval/report?output=xml' % (API_HOST, portfolio_id), auth=auth, data=portfolio)
    response.raise_for_status()
    document = get_document(response.text)
    for report in document.iter('report'):
        print('  Report: %s for %s (ID %s, created %s)' % (report.attrib['type'], report.attrib['death-date'], report.attrib['id'],
              report.attrib['report_time_created']))
    if document.find('more').text == 'true':
        print('  ...and more')
except Exception as e:
    print('  FAILED (GET /portfolio/{portfolio-id}/estateval/report error: %s)' % repr(e))
    sys.exit(-1)
print('  Succeeded')

# Get the report data --------------------------------------------------------
print('Getting the report data...')
try:
    response = requests.get('https://%s/portfolio/%s/estateval/report/%s?output=xml' % (API_HOST, portfolio_id, report_id), auth=auth)
    response.raise_for_status()
except Exception as e:
    print('  FAILED (POST /portfolio/{portfolio-id}/estateval/report/{report-id} error: %s)' % repr(e))
    sys.exit(-1)
print('  Succeeded')

print("\n%s" % response.text)
