#!/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
from geojson import Polygon, Feature, FeatureCollection, dump

import cgi
import sqlite3
import sys
import json


# Webページ情報取得
data = sys.stdin.read()
params = json.loads(data)


df = pd.read_csv('testdata_4_5.csv', dtype = 'object')


# 属性カラムを判断し左からattr1, attr2, .. と命名
attr_columns = df.columns.drop(['id', 'timestamp', 'lat', '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['timestamp2'] = pd.to_datetime(df['timestamp'])
df['lat'] = df['lat'].astype(float)
df['lng'] = df['lng'].astype(float)
df['value'] = df['value'].astype(float)
# 時間を持たせる
df['year'] = df['timestamp2'].dt.year
df['month'] = df['timestamp2'].dt.month
df['date']  = df['timestamp2'].dt.day
df['hour']  = df['timestamp2'].dt.hour
df['dow'] = df['timestamp2'].dt.strftime("%a")
# 平日・休日を作成、祝日は考慮しない(不変でないため)
df.loc[df['dow'].isin(['Mon', 'Tue', 'Wed', 'Thu', 'Fri']), 'holiday'] = '平日'
df.loc[df['dow'].isin(['Sat', 'Sun']), 'holiday'] = '休日'
df['yyyymmdd'] = df['timestamp2'].dt.date
df_all = df.copy()

selected_year = ['']
selected_month = ['']
selected_date = ['']
selected_hour = ['']
selected_dow = ['']
selected_holiday = ['']
selected_attr1 = ['']
selected_attr2 = ['']
selected_attr3 = ['']
selected_attr4 = ['']
selected_attr5 = ['']


if len(params['year']) != 0:
    selected_year =  [int(i) for i in params['year']]
if len(params['month']) != 0:
    selected_month =  [int(i) for i in params['month']]
if len(params['date']) != 0:
    selected_date =  [int(i) for i in params['date']]
if len(params['time']) != 0:
    selected_hour =  [int(i) for i in params['time']]
if len(params['yobi']) != 0:
    selected_dow =  params['yobi']
if len(params['holyday']) != 0:
    selected_holiday = params['holyday']
if len(params['attr1']) != 0:
    selected_attr1 = params['attr1']
if len(params['attr2']) != 0:
    selected_attr2 = params['attr2']
if len(params['attr3']) != 0:
    selected_attr3 = params['attr3']
if len(params['attr4']) != 0:
    selected_attr4 = params['attr4']
if len(params['attr5']) != 0:
    selected_attr5 = params['attr5']


if selected_year != ['すべて']:
    df = df[df['year'].isin(selected_year)]
if selected_month != ['すべて']:
    df = df[df['month'].isin(selected_month)]
if selected_date != ['すべて']:
    df = df[df['date'].isin(selected_date)]
if selected_hour != ['すべて']:
    df = df[df['hour'].isin(selected_hour)]
if selected_holiday != ['すべて']:
    df = df[df['holiday'].isin(selected_holiday)]
if 'selected_attr1' in locals():
    if selected_attr1 != ['すべて']:
        df = df[df['attr1'].isin(selected_attr1)]
if 'selected_attr2' in locals():
    if selected_attr2 != ['すべて']:
        df = df[df['attr2'].isin(selected_attr2)]
if 'selected_attr3' in locals():
    if selected_attr3 != ['すべて']:
        df = df[df['attr3'].isin(selected_attr3)]
if 'selected_attr4' in locals():
    if selected_attr4 != ['すべて']:
        df = df[df['attr4'].isin(selected_attr4)]
if 'selected_attr5' in locals():
    if selected_attr5 != ['すべて']:
        df = df[df['attr5'].isin(selected_attr5)]


df_selected = df.copy().reset_index(drop=True)

if len(df_selected) == 0:
    result = {}
    print("Content-type: application/json")
    print("\n\n")
    print(json.dumps(result))

    print('\n')
    exit()
    
user_id_list = []
replace_min = 99999999999999999
replace_max = 0

id_list = [*df_selected.groupby("id").groups]

groups = df_selected.groupby(df_selected.id)

for i in range(len(id_list)):
    id_group = groups.get_group(id_list[i])
    id_group['timestamp'] = pd.to_datetime(id_group['timestamp'])
    id_group = id_group.sort_values('timestamp')
    user = {}
    path_all = []
    time_all = []
    j = 0
    for index, row in id_group.iterrows():
        user = {}
        user["vendor"] = i
        if j==0 :
            lat_1 = float(row['lat'])
            lon_1 = float(row['lng'])
            path_1 = [lon_1,lat_1]
            time_1 = int(row['timestamp'].timestamp())
        else :
            lat_2 = float(row['lat'])
            lon_2 = float(row['lng'])
            path_2 = [lon_2,lat_2]
            time_2 = int(row['timestamp'].timestamp())
            user["path"] = [path_1,path_2]
            user["timestamps"] = [time_1,time_2]

            if time_2 > replace_max :
                replace_max = time_2

            if time_2 < replace_min :
                replace_min = time_2

            lat_1 = float(row['lat'])
            lon_1 = float(row['lng'])
            path_1 = [lon_1,lat_1]
            time_1 = int(row['timestamp'].timestamp())
            
            user_id_list.append(user)
        j = j+1

    i = i+1

with open('mod5.json', 'w') as f:
    json.dump(user_id_list, f, indent=2)

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

print('\n')
