# -*- coding: utf-8 -*-

import datetime
import dingguo
import email
import ioex
import re

def parse_order_confirmation_mail(mail):

    assert isinstance(mail, email.message.Message)

    msg = mail.get_payload()[0]
    if type(msg.get_payload()) is list:
        msg = msg.get_payload()[0]
    msg_text = msg.get_payload(decode = True).decode('utf8')

    # msg_text = re.sub(
    #     r'<[^>]+>',
    #     '',
    #     HTMLParser.HTMLParser().unescape(msg.get_payload(decode = True).decode('utf8'))
    #     )

    order_match = re.search(
        ur'(?P<order_id_label>Booking code|Buchungscode):\s+(?P<order_id>[\d ]+)\s+'
            + ur'(Customer number|Kundennummer):\s+(?P<customer_id>PV\d+)\s+'
            + ur'(Booking date|Buchungsdatum):\s+(?P<order_date>.* \d{4})\s',
        msg_text,
        re.MULTILINE | re.UNICODE
        )
    order_match_groups = order_match.groupdict()

    if order_match_groups['order_id_label'] == 'Buchungscode':
        with ioex.setlocale('de_AT.UTF-8'):
            order_date = datetime.datetime.strptime(
                order_match_groups['order_date'],
                '%d. %b %Y',
                )
    else:
        with ioex.setlocale('en_US.UTF-8'):
            order_date = datetime.datetime.strptime(
                order_match_groups['order_date'],
                '%b %d, %Y',
                )

    order = dingguo.Order(
        u'oebb',
        order_match_groups['order_id'],
        order_date.date(),
        customer_id = order_match_groups['customer_id'],
        )

    item_match = re.search(
        ur'(?P<price_brutto_currency>.) ?(?P<price_brutto>\d+(\.|,)\d+)'
            + ur'[\W\w]+'
            + ur'(Your Bookings?|Ihre Buchung)\s+'
            + ur'(?P<departure_point>.*)\s+>\s+(?P<destination_point>.*)',
        msg_text,
        re.MULTILINE | re.UNICODE
        )
    item = item_match.groupdict()
    order.items.append(dingguo.Transportation(
        name = u'Train Ticket',
        price_brutto = dingguo.Sum(
            float(item['price_brutto'].replace(',', '.')),
            item['price_brutto_currency'],
            ),
        departure_point = item['departure_point'],
        destination_point = item['destination_point'],
        ))

    return [order]