#!/usr/bin/python
# -*- coding: koi8-r -*-
import sys
sys.path.insert(1,'../modules/')
import locale
import profile

from ReadMap import ReadMap
from FindPath import FindPath

#profile.run('ReadMap((open("../data/Moscow/Moscow.cty"), open("../data/Moscow/Metro.map"), open("../data/Moscow/Metro.trp"), open("../data/Moscow/Moscow.vec")))')

MetroMap = ReadMap((open("../data/Moscow/Moscow.cty"),
                    open("../data/Moscow/Metro.map"),
                    open("../data/Moscow/Metro.trp"),
                    open("../data/Moscow/Moscow.vec")))
#MetroMap = ReadMap(open("../data/London/Metro.ini"))

Finder = FindPath(MetroMap.Graph, 5)

if len(sys.argv) == 2 and sys.argv[1] == 'timetest':
        import datetime
        maxtime = datetime.timedelta(0)
        maxtimestat = datetime.timedelta(0)
        maxjumps = 0
        frst = 0
        tost = 0
        for fr in MetroMap.Stations.values():
                if fr['uc']:
                        continue
                print "%d %s (%s)" % (fr['number'], fr['name'], MetroMap.Lines[fr['line']]['name'])
                startstat = datetime.datetime(100, 1, 1).now()
                for to in MetroMap.Stations.values():
                        if to['uc']:
                                continue
                        start = datetime.datetime(100, 1, 1).now()
                        plist = Finder.waves_accurate(fr['number'], to['number'], MetroMap.WaitLen)
                        if not len(plist):
                                print 'not found:', fr['number'], to['number'], fr['name'], to['name']
                                sys.exit(0)
                        finish = datetime.datetime(100, 1, 1).now()
                        if (finish - start) > maxtime:
                                maxtime = finish - start
                                frst = fr
                                tost = to
                                print maxtime, fr['number'], to['number'], '(' + fr['name'], to['name'] + ')'

                finishstat = datetime.datetime(100, 1, 1).now()
                md = finishstat - startstat
                if md > maxtimestat:
                        maxtimestat = md
                        print 'Max:', md

        sys.exit(0)

if len(sys.argv) != 3:
        print "Usage:"
        print sys.argv[0], "timetest"
        print sys.argv[0], "'from station [, line]' 'to station [, line]'"
        print "station and line names can be specifed partialy"

        sys.exit(0)

def findstlist(st):
        if st.isdigit():
                return [int(st)]
        pair = map(lambda a: a.lstrip().rstrip(), st.split(','))
        lst = list()
        for s in MetroMap.Stations.values():
                if s['name'].lower().startswith(pair[0].lower()):
                        lst.append(s['number'])
        if len(pair) == 2:
                nlst = list()
                for l in MetroMap.Lines.values():
                        if l['name'].lower().startswith(pair[1].lower()):
                                for s in lst:
                                        if s in l['stations']:
                                                nlst.append(s)
                lst = nlst

        return lst

(nlcode, enc) = locale.getdefaultlocale()

fromlist = findstlist(unicode(sys.argv[1], enc))
tolist = findstlist(unicode(sys.argv[2], enc))

def printpath(path):
        step = 0
        pvl = 0
        for i in path:
                if step > 0:
                        if MetroMap.Stations[i]['line'] != MetroMap.Stations[pvl]['line']:
                                print
                                print "%s: %s" % (MetroMap.Lines[MetroMap.Stations[i]['line']]['name'], MetroMap.Stations[i]['name']),
                        else:
                                print '->', MetroMap.Stations[i]['name'],
                else:
                        print "%s: %s" % (MetroMap.Lines[MetroMap.Stations[i]['line']]['name'], MetroMap.Stations[i]['name']),
                pvl = i
                step += 1
        print
        print

for f in fromlist:
        for t in tolist:
                sf = MetroMap.Stations[f]
                st = MetroMap.Stations[t]
                print 'Going from "%s (%s)" to "%s (%s)"' % (sf['name'], MetroMap.Lines[sf['line']]['name'],
                                                             st['name'], MetroMap.Lines[st['line']]['name'])
                plist = Finder.waves_accurate(f, t, MetroMap.WaitLen)
                if len(plist):
                        for p in plist:
                                print 'Минут -', p[0], 'Пересадок -', p[1]
                                printpath(p[2:])
