#!/usr/local/bin/python3
# -*- Coding: utf-8 -*-

import cgi
import time
from importlib import import_module
from operator import truediv
from db import database
from makepage_input import makepage_input
from makepage_show import makepage_show
from makepage_analyze import makepage_analyze

# File
with open('index.html', mode='r') as f:
    index_html = f.read()

#cgiオブジェクト作成
params = cgi.FieldStorage()

#パラメータを変数に格納
func = params.getfirst('func', '')
nowdate = params.getfirst('now_date', '')
item = params.getfirst('item_list', '0')
assessment = params.getfirst('assessment_list', '0')
comment = params.getfirst('comment', '')

# DB登録
if  nowdate != '' and item != '' and assessment != '':
    # DB
    db = database("entry.db")
    db.insert_record(int(item), int(assessment), comment)
    #comment = nowdate + ':' + item + ':' + assessment + ':' + comment
    #db.post(comment)
    #bodycontents += '<meta http-equiv="REFRESH" content="2;URL=/cgi-bin/server.py?func=2"><h1>Post Successed.</h1>'


# else:
#   print('パラメータなし')

bodycontents =''

if func == '1' :
    # 登録
    bodycontents = makepage_input()

if func == '2' :    
    # 記録
    bodycontents = makepage_show()

if func == '3' :
    # 分析
    bodycontents = makepage_analyze()

#Web
print("Content-type: text/html\n")
print("")

htmlText = index_html.format(
    header = 'JIBUN_ANALYSE',
    title = 'ジブンアナライズ',
    content = bodycontents
)
#print( htmlText.encode('utf-8', 'ignore').decode('utf-8') )
print( htmlText )

# htmlText = '''
# <!DOCTYPE html>
# <html>
#     <head>
#     <meta charset="utf-8" />
#     <link rel="stylesheet" type="text/css" href="../css/charts.min.css"><!--パス位置注意-->
#     </head>
#     <body bgcolor="lightyellow">
#         <h1>こんにちは</h1>
#         <p>入力値の積は&nbsp;%s<br/></p>
#         <hr/>
#         <a href="../form1.html">戻る</a>
#         <div id="my-chart" style="height: 550px;">
#             <table class="charts-css line" id="my-line">
#                 <tbody>   
#                 <tr><th scope="row">い</th><td style="--start: 0.8;--size: 0.5;"></td></tr>
#                 <tr><th scope="row">い</th><td style="--start: 0.8;--size: 0.5;"></td></tr>
#                 <tr><th scope="row">い</th><td style="--start: 0.8;--size: 0.5;"></td></tr>
#                 </tbody>
#             </table>
#         </div>
#     </body>
# </html>
# '''%(times(v1,v2)) # 入力値の積を%sの箇所に埋める
#print( htmlText.encode("cp932", 'ignore').decode('cp932') )
#print( htmlText.encode('utf-8', 'ignore').decode('utf-8') )

#入力値が数字ならその積を返す関数
def times(a, b):
    try:
        a=int(a)
        b=int(b)
        return str(a*b)
    except ValueError:
        return('数値じゃないので計算できません(>_<)')
