#!/usr/bin/python
# -*- coding: utf-8 -*-
# 必要なライブラリ
import pandas as pd
pd.set_option('display.max_columns', 99999)
pd.set_option('display.max_rows', 500)
import pandas as pd
from pandas import Series, DataFrame
import datetime
from datetime import timedelta
import worldmesh

import cgi
import sqlite3
import sys
import json

data = sys.stdin.read()
params = json.loads(data)


df = pd.read_csv('testdata_4_5.csv', dtype = 'object')
# 緯度経度の情報を125mメッシュに落とし込む
for i in range(len(df)):
    mesh125 = worldmesh.cal_meshcode6(float(df.loc[i, 'lat']), float(df.loc[i, 'lng']))
    mesh_lat_lng = worldmesh.meshcode_to_latlong_grid(mesh125)
    c_lat = (mesh_lat_lng['lat0'] + mesh_lat_lng['lat1']) / 2
    c_lng = (mesh_lat_lng['long0'] + mesh_lat_lng['long1']) / 2
    # areaをmeshで上書きし、メッシュをエリアとして扱う。エリアの緯度経度はメッシュの中心とする。
    df.loc[i, 'area'] = str(mesh125)[2:]
    df.loc[i, 'area_lat'] = c_lat
    df.loc[i, 'area_lng'] = c_lng

aaa = df.drop(['lat', 'lng'], axis=1)
aaa.to_csv('testdata_4_custom.csv',index=False)


# 属性カラムを判断し左からattr1, attr2, .. と命名
attr_columns = aaa.columns.drop(['id', 'timestamp', 'area', 'area_lat', 'area_lng', 'value'])
attrs = [] # attr1, attr2, ...→この後の処理に使用 
attrs_name = [] #  csv内のもとの名前→HTML内のフィルターの題名や、属性分析の属性選択リストに使用
for i, column in enumerate(attr_columns):
    df.rename(columns={column: f'attr{i+1}'}, inplace=True)
    attrs.append(f'attr{i+1}')
    attrs_name.append(column)





# 型指定（attr情報はobjectのまま）
df['id'] = df['id'].astype(str)
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['area'] = df['area'].astype(str)
df['area_lat'] = df['area_lat'].astype(float)
df['area_lng'] = df['area_lng'].astype(float)
df['value'] = df['value'].astype(float)
# 時間を持たせる
df['year'] = df['timestamp'].dt.year
df['month'] = df['timestamp'].dt.month
df['date']  = df['timestamp'].dt.day
df['hour']  = df['timestamp'].dt.hour


result = {}
result["area_list"] = [*df.groupby("area").groups]
result["year_list"] = [*df.groupby("year").groups]
result["month_list"] = [*df.groupby("month").groups]
result["date_list"] = [*df.groupby("date").groups]
result["hour_list"] = [*df.groupby("hour").groups]
result["holiday_list"] = ['平日', '休日']
result["week_list"] = ['Mon', 'Tue', 'Wed','Thu' ,'Fri','Sat','Sun']
for i in range(5):
    if f'attr{i+1}' in df.columns:
        result[f'attr{i+1}_list'] = [*df.groupby(f'attr{i+1}').groups]
    else:
        result[f'attr{i+1}_list'] = ['すべて']
result["attrs_name"] = attrs_name

result["init_year"] = df.at[df.index[0],'year'].astype(str)
result["init_month"] = df.at[df.index[0],'month'].astype(str)

print("Content-type: application/json")
print("\n\n")
print(json.dumps(result))

print('\n')



