import json
import requests
import xmltodict

from lxml import etree
from usps import USPSApi as USPSApiBase


class USPSApi(USPSApiBase):
    urls = {
        'tracking': 'TrackV2{test}&XML={xml}',
        'label': 'eVS{test}&XML={xml}',
        'validate': 'Verify&XML={xml}',
        'rate': 'RateV4&XML={xml}',
    }

    def get_rate(self, *args, **kwargs):
        return Rate(self, *args, **kwargs)


class Rate:

    def __init__(self, usps, request, **kwargs):
        xml = etree.Element('RateV4Request', {'USERID': usps.api_user_id})
        etree.SubElement(xml, 'Revision').text = '2'
        package = etree.SubElement(xml, 'Package', {'ID': '0'})
        etree.SubElement(package, 'Service').text = request['service']
        etree.SubElement(package, 'ZipOrigination').text = request['zip_origination']
        etree.SubElement(package, 'ZipDestination').text = request['zip_destination']
        etree.SubElement(package, 'Pounds').text = request['pounds']
        etree.SubElement(package, 'Ounces').text = request['ounces']
        etree.SubElement(package, 'Container').text = request['container']
        etree.SubElement(package, 'Width').text = request['width']
        etree.SubElement(package, 'Length').text = request['length']
        etree.SubElement(package, 'Height').text = request['height']
        etree.SubElement(package, 'Girth').text = request['girth']
        etree.SubElement(package, 'Machinable').text = request['machinable']

        self.result = usps.send_request('rate', xml)
