# Classes for measurement units
#
# Copyright (C) 1996-2001 Chris Lawrence
# This file may be freely distributed under the terms of the RoutePlanner
# license.  A copy should appear as 'LICENSE' in the archive that this
# file was included in.
#
# db = rpdbase.RPDatabase(filename) - Load a database
# db.Open(filename) - Replace the database by loading another
# db.Save(filename) - Write the database
#
# db.cities - The list of city instances
# db.routes - The list of route instances

UNITS_METRIC   = 'km'
UNITS_US = 'mi'
UNITS_IMPERIAL = 'mi2'

VALID_UNITS = [UNITS_METRIC, UNITS_US, UNITS_IMPERIAL]

UNITS = { 'Metric (km, l)' : UNITS_METRIC,
          'U.S. (mi, gal = 3.785 liters)' : UNITS_US,
          'Imperial (mi, gal = 4.546 liters)' : UNITS_IMPERIAL}

class Distance:
    def __init__(self, initval=0.0, units=UNITS_US):
        self.value = float(initval)

        if units == UNITS_IMPERIAL:
            units = UNITS_US

        self.units = units

    def __float__(self):
        return self.value

    def __add__(self, other):
        if type(other) == type(self):
            if self.units == other.units:
                return Distance(self.value+other.value, self.units)
            else:
                return self+other.AsUnit(self.units)

    def __div__(self, other):
        if type(other) == type(self):
            if self.units == other.units:
                return Distance(self.value/other.value, self.units)
            else:
                return self/other.AsUnit(self.units)

    def __str__(self):
        return '%d %s' % (self.value, self.units)

    def __cmp__(self, other):
        if type(other) != type(self):
            return cmp(self.value, other)
        elif self.units == other.units:
            return cmp(self.value, other.value)
        else:
            return cmp(self.value, other.AsUnit(self.units))

    def AsUnit(self, units):
        if units == self.units:
            return self

        if units == UNITS_IMPERIAL and self.units == UNITS_US:
            return self

        if units == UNITS_METRIC:
            return Distance(self.value * 1.609344, units)

        return Distance(self.value / 1.609344, units)

def ConvertEfficiency(amt, oldunits, newunits):
    if oldunits == newunits: return amt

    if oldunits == UNITS_METRIC:
        if newunits == UNITS_US:
            return 235.21458 / amt
        else:
            return 282.48094 / amt
    elif oldunits == UNITS_US:
        if newunits == UNITS_METRIC:
            return 235.21458 / amt
        else:
            return amt * 1.20094
    else:
        if newunits == UNITS_METRIC:
            return 282.48094 / amt
        else:
            return amt / 1.20094
