def save_direct_trains(start_trains, end_trains):
	"""save direct edges

	"""
	direct_plans = []
	if len(start_trains) <= len(end_trains):
		for (k,v) in start_trains.items():
			if k in end_trains and v < end_trains[k]: # direct
				k_train = Train.objects(train_no=k).get()
				direct_plan = Direct_Plan(v, end_trains[k], k_train)
				direct_plans.append(direct_plan)		
	else:
		for (k,v) in end_trains.items():
			if k in start_trains and v > start_trains[k]: # direct
				k_train = Train.objects(train_no=k).get()
				direct_plan = Direct_Plan(start_trains[k], v, k_train)
				direct_plans.append(direct_plan)		
	# if direct_plans:
	return direct_plans
def gettrain(train_code):
	#mc_key = md5("stations")
	#stations = MC.get(mc_key) 
	train_code = str.upper(train_code)
	train = Train.objects(__raw__={'board_train_code':{'$all':[train_code,]}}).get()
	if 'callback' in request.query:
		callback = request.query.callback
		response.content_type = 'application/javascript'
		return callback + '(' + train.to_json() + ');'
	else:
		response.content_type = 'application/json'
		return json.dumps(train.to_dict(), indent=4) 
def save_tranfer_one_plans(start_trains, end_trains):
	"""save one tranfer plans """
	tranfer_one_plans = [] #save tranfer result

	trains = lambda train:[(t,train[t.train_no]) for t in Train.objects(__raw__={"train_no":{"$in":train.keys()}})]

	start_train_seqs = trains(start_trains)
	start_sta_info =lambda d: dict([(s.sta_name, s) for s in d[0].edges if s.seq_no > d[1]]) #s.arrive_time,s.city_same
	start_trains_stas_v = map(start_sta_info, start_train_seqs)

	end_train_seqs = trains(end_trains)
	end_sta_info =lambda d: dict([(s.sta_name, s) for s in d[0].edges if s.seq_no < d[1]])#s.depart_time,s.city_same
	end_trains_stas_ev = map(end_sta_info, end_train_seqs)
		
	for i,sl in enumerate(start_trains_stas_v):
		set_one = set(sl.keys())
		train_one = start_train_seqs[i]
		for j,el in enumerate(end_trains_stas_ev):
			train_two = end_train_seqs[j]
			if len(train_one[0].cross_bureaus) == 1 and len(train_two[0].cross_bureaus) == 1:
				break #tranfer is not taking place in two bureau trains
			set_two = set(el.keys())
			set_union = set_one & set_two
			same_city_sta = [(st1,st2) for st1 in set_one - set_union for st2 in set_two - set_union \
							if sl[st1].city_same and sl[st1].city_same==el[st2].city_same]
			
			union_sets_sta = []
			union_sets_sta = list(set_union)
			union_sets_sta.extend(same_city_sta)

			if union_sets_sta:
				try:
					#union_sets_sta_dict = [] 
					#union_sets_sta_dict = zip(union_sets_sta, union_sets_sta)
					#union_sets_sta_dict.extend(same_city_sta)
					union_sets_connct_time = []
					union_sets_connct_time = [connect_time(sl[t].arrive_time, el[t].depart_time) for t in set_union]
					union_sets_connct_time.extend([connect_time(sl[t1].arrive_time, el[t2].depart_time) for (t1,t2) in same_city_sta])
				except TypeError, e:
					print "type error"
				except Exception, ex:
					print "other error"
					
				#union_sets_all = dict(zip(union_sets_sta,union_sets_connct_time))
				#union_sets_filter = sorted(union_sets_all.items(), key=lambda x: x[1])
				transit_time = max(union_sets_connct_time)
				for i,x in enumerate(union_sets_connct_time):
					if x == transit_time and i<len(set_union):
						transit_sta = union_sets_sta[i]
						transit_sta_seqs = (sl[transit_sta].seq_no, el[transit_sta].seq_no)
						tranfer_one = Tranfer_One_Plan(train_one[0],train_one[1], train_two[0],train_two[1], transit_sta_seqs, transit_sta,transit_time)
						tranfer_one_plans.append(tranfer_one)
						break
					elif x == transit_time and i>=len(set_union):
						if_city_same = True
						transit_stas = union_sets_sta[i]
						transit_sta_seqs = (sl[transit_stas[0]].seq_no, el[transit_stas[1]].seq_no)
						tranfer_one = Tranfer_One_Plan(train_one[0],train_one[1], train_two[0],train_two[1], transit_sta_seqs, transit_stas,transit_time,if_city_same)
						tranfer_one_plans.append(tranfer_one)
						break
					else:
						continue
def save_tranfer_two_plans( start_sta, start_trains_kv, end_sta, end_trains_kv ):
	"""
	tranfer two plan includes one direct plan and tranfer one plan
	"""
	#results,start_trains,end_trains = save_direct_plans(start_sta, end_sta)
	direct_train = Train.objects( train_no = start_trains_kv)