import csv
import urllib.request
import json
import datetime
import random

# 変数の初期化

agent_dict = {}
agent_status_dict = {}
agent_name_dict = {}
agent_glb_dict = {}
sub_glb_dict = {}

speed = ['normal', 'fast', 'slow']

# 再生速度
my_multiplier = 21600

# 表示高さ
h_visible = 1000
h_unvisible = -1000
h_ship = 0

# 開始時間、終了時間（''の場合はファイル読込）
starttime = ''
endtime = ''


# 日時をCesium形式に変換
def format_date(one_str):
	tdatetime = datetime.datetime.strptime(one_str, '%Y/%m/%d %H:%M:%S')
	return(tdatetime.strftime('%Y-%m-%dT%H:%M:%SZ'))	

# ship　のjson生成
def compact_position_ship():
	n_view = 0
	rtn_str = ''
	for key, value in agent_dict.items():
		# position_str = agent_dict[key]
		# position_array = position_str.split('\n')
		position_array = value.split('\n')
		last_token = ''
		repeat_flag = False
		for token in position_array:
			t_array = token.split(',')
			new_token = t_array[1] + "," + t_array[2] + "," + t_array[3]
			if (last_token != new_token) or (last_status != t_array[4]):
				if last_token == '':
					# 初めての場合
					rtn_str += out_agent_header(key, n_view)
					n_view += 1
					rtn_str += '\t\t' + t_array[0] + "," + new_token
				else:
					if last_status != t_array[4]:
						rtn_str += ',\n' + '\t\t' + last_step + "," + last_token
						#rtn_str += out_agent_footer(key, last_status, last_place, last_dest)
						rtn_str += out_agent_footer(key, last_status)
						rtn_str += out_agent_header(key, n_view,)
						n_view += 1
						rtn_str += '\t\t' + t_array[0] + "," + new_token
					else:
						if repeat_flag:
							rtn_str += ',\n' + '\t\t' + last_step + "," + last_token
						rtn_str += ',\n' + '\t\t' + t_array[0] + "," + new_token
				repeat_flag = False
			else:
				repeat_flag = True
			

			last_token = new_token
			last_step = t_array[0]
			last_status = t_array[4]



		# 終了処理
		rtn_str += ',\n' + '\t\t' + last_step + "," + last_token
		rtn_str += out_agent_footer(key, t_array[4])
		#rtn_str += out_agent_footer(key, t_array[4])
	
	return(rtn_str)
	
# status　のjson生成
def compact_position_status(position_str):
	position_array = position_str.split('\n')
	last_token = ''
	rtn_str = ''
	for token in position_array:
		t_array = token.split(',')
		new_token = t_array[1] + "," + t_array[2] + "," + t_array[3]
		if last_token != new_token:
			if last_token == '':
				# 初めての場合
				rtn_str = '\t\t' + t_array[0] + "," + new_token
			else:
				if last_status != t_array[4]:
					rtn_str += ',\n' + '\t\t' + last_step + "," + last_token
				rtn_str += ',\n' + '\t\t' + t_array[0] + "," + new_token
		last_token = new_token
		last_step = t_array[0]
		last_status = t_array[4]
	
	return(rtn_str)

# agentのheaderのjson生成
def out_agent_header(key, n):
	json_str = ', {\n'
	json_str += '\t"id" : "' + str(key) + '_' + str(n) + '_else' +  '",\n'
	json_str += '\t"name" : "agent",\n'
	json_str += '\t"description" : "' + agent_name_dict[key] + '",\n'
	json_str += '\t"position" : {\n'
	json_str += '\t\t"epoch" : "' + starttime + '",\n'
	json_str += '\t\t"cartographicDegrees" : [\n'

	return(json_str)
	
# agentのfooterのjson生成
#def out_agent_footer(key, one_status):
def out_agent_footer(key, one_status):
	json_str = '\n\t\t]\n'
	json_str += '\t},\n'
	glb_key = agent_name_dict[key]
	value = agent_glb_dict[glb_key]['main_model']
	
	if one_status == agent_glb_dict[glb_key]['status']:
		value = agent_glb_dict[glb_key]['sub_model']
	
	if one_status == speed[0]:
		point_color = '\t\t\t"rgba": [255, 255, 255, 255]\n'
	elif one_status == speed[1]:
		point_color = '\t\t\t"rgba": [255, 0, 0, 255]\n'
	else:
		point_color = '\t\t\t"rgba": [255, 255, 0, 255]\n'


	json_str += '\t"point": {\n'
	json_str += '\t\t"color": {\n'
	json_str += point_color
	json_str += '\t\t},\n'
	json_str += '\t\t"pixelSize": 10,\n'
	json_str += '\t\t"heightReference":"CLAMP_TO_GROUND"\n'
	json_str += '\t},\n'
	json_str += '\t"model":{\n'
	json_str += '\t\t"gltf": [{"uri": "' + value + '.glb"}],\n'
	json_str += '\t\t"scale":40.0,\n'
	json_str += '\t\t"show":true,\n'
	json_str += '\t\t"minimumPixelSize":100,\n'
	json_str += '\t\t"maximumScale":50,\n'
	json_str += '\t\t"heightReference":"CLAMP_TO_GROUND"\n'
	json_str += '\t},\n'

	json_str += '\t"orientation":{\n'
	json_str += '\t\t"velocityReference": "#position"\n'
	json_str += '\t}\n'
	json_str += '}'	
	return(json_str)


			



# heder のjson生成
def get_json_header():
	json_str = '[{\n'
	json_str += '\t"id" : "document",\n'
	json_str += '\t"name" : "circuit_sim",\n'
	json_str += '\t"version" : "1.0",\n'
	json_str += '\t"clock": {\n'
	json_str += '\t\t"interval" : "' + starttime + '/' + endtime + '",\n'
	json_str += '\t\t"currentTime" : "' + starttime + '",\n'
	json_str += '\t\t"multiplier" : ' + str(my_multiplier) + '\n'
	json_str += '\t}\n'
	json_str += '}'

	return(json_str)

# footer のjson生成
def get_json_footer():
	json_str = '\n]\n'

	return(json_str)

# メイン処理

with open('log_agents.czml', mode='w', encoding='utf-8') as fo:
	with open('log_detail_racing.csv', mode='r', encoding='utf-8-sig') as fi:
		with open('agents_glb.csv', mode='r', encoding='utf-8') as fr:

			reader = csv.reader(fr)
			next(reader)

			for row in reader:
				key = row[0]

				sub_glb_dict = {}
				sub_glb_dict['main_model'] = row[1]
				sub_glb_dict['sub_model'] = row[2]
				sub_glb_dict['place'] = row[3]
				sub_glb_dict['dest'] = row[4]
				if row[5] == '':
					sub_glb_dict['locate'] = 0.0
				else:
					sub_glb_dict['locate'] = row[5]
				sub_glb_dict['status'] = row[6]

				agent_glb_dict[key] = sub_glb_dict

			ct = 0
			for row in csv.reader(fi):
				if row[0] == 'sim_datetime':
					pass
				else:
					one_sim_datetime = row[0]
					if ct == 1:		# 0行目はヘッダなので、1行目で処理
						dt_list = one_sim_datetime.split(' ')
						starttime = format_date(dt_list[0] + ' ' + dt_list[1])
						print(f" starttime: {starttime}")
					one_step = row[1]
					one_agent_name = row[2]
					one_id = row[3]
					one_action = row[4]
					one_longitude = row[5]
					one_latitude = row[6]
					one_elevation = float(row[7])
					one_status = row[8]
					
					if row[3] in agent_dict:
						# 既にエントリしている場合
						one_token = ',\n' + '\t\t' + str(one_step) + ',' + str(one_longitude) + ',' + str(one_latitude)
						agent_dict[one_id] += one_token + ',' + str(one_elevation)
					else:
						# 初めてのエントリの場合
						agent_name_dict[one_id] = str(one_agent_name)
						one_token = '\t\t' + str(one_step) + ',' + str(one_longitude) + ',' + str(one_latitude)
						agent_dict[one_id] = one_token + ',' + str(one_elevation)

					
					# one_status_conditionの追加
					agent_dict[one_id] += ',' + one_status

				ct += 1
			endtime = format_date(one_sim_datetime)
			print(f" endtime: {endtime}")

		# czml出力
		out_str = get_json_header()
		out_str += compact_position_ship()
		out_str += get_json_footer()
		fo.write(out_str)

