# Code for the City class
#
# 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.

import string, rpdbase
from rpcountry import expand_country

invalidformat = 'rpcity.invalidformat'

class City:
    def __init__(self, data=None):
        if data:
            items = string.split(data[0], ', ')
            self.city = items[0]
            if len(items) > 1:
                self.state = items[1]
            else:
                self.state = ''

            # Kludges
            if self.state == 'Quebec':
                self.state = 'Québec'
            
            if len(data) > 4:
                self.country = data[4]
            else:
                self.country = rpdbase.autodetect_country(self.state)

            if data[1]:
                self.intersection = 1
            else:
                self.intersection = 0
            self.longitude = float(data[2])
            self.latitude = float(data[3])
            
            if self.state:
                self._printable = self.city + ', ' + self.state
            else:
                self._printable = self.city + ', ' + expand_country(self.country)
        else:
            self.city = self.state = self.country = ''
            self.longitude = self.latitude = 0.0
            self.intersection = 0
            self._printable = '(Null)'
        
        self.roads = []

    def update_info(self, city, state, country='us', longitude=0.0,
                    latitude=0.0, intersection=0):
        self.city = city
        self.state = state
        self.country = country
        self.intersection = intersection
        self.longitude = float(longitude)
        self.latitude = float(latitude)
        if state:
            self._printable = city + ', ' + state
        else:
            self._printable = city + ', ' + expand_country(country)

    def __repr__(self):
        interchange = ''
        if self.intersection: interchange = 'I'

        if self.state:
            city = self.city+', '+self.state
        else:
            city = self.city

        return '%s|%s|%.3f|%.3f|%s' % (city, interchange, self.longitude,
                                       self.latitude, self.country)
    def __str__(self):
        return self._printable

    def __cmp__(self, other):
        return cmp(self.city, other.city) or cmp(self.state, other.state) or \
               cmp(self.country, other.country)
    
    def __hash__(self):
        return id(self)

    def __del__(self):
        del self.roads

    def printable(self, include_country=0):
        if not self.state:
            return '%s, %s' % (self.city, expand_country(self.country))
        elif include_country:
            return '%s, %s' % (self._printable, expand_country(self.country))
        else:
            return self._printable
# End of City
