#https://hexadrive.jp/author/webmanager/page/623/
'''
TODO
複数フォームsubmit
O Address already in use 対策　ー＞　lsof -i:8000 kill xxxでプログラムキルを！
ちゃんとサーバー公開可能なのか？
SELECT等、SQLに耐えられるのか？
'''

import http.server
from importlib import import_module
from operator import truediv
import urllib.parse
import time
import random

from db import database

#file
with open('index.html', mode='r') as f:
    index_file = f.read()
with open('inputForm.html', mode='r') as f:
    inputForm_file = f.read()

# DB
db = database("entry.db")

class http_handler(http.server.BaseHTTPRequestHandler):

    def do_GET(self):
        # リクエスト内容をパース
        request = urllib.parse.urlparse(self.path)
        params = dict(urllib.parse.parse_qsl(request.query))
 
        # レスポンスを生成
        body = self.body(request.path, params)
        self.send_response(200)
        self.send_header('Content-type', 'text/html; charset=utf-8')
        self.send_header('Content-length', len(body))
        self.end_headers()
        self.wfile.write(body)
        
    def body(self, request, params):

        bodycontents = ''

        if request == "/fun1":
            # 登録
            bodycontents += inputForm_file.format()

        elif request == "/fun2":
            # 記録
            for e in sorted(db.get(), key=lambda e: e[2], reverse=True):
               bodycontents += '<section class="panel">'
               bodycontents += '<header>{0}</header>'
               bodycontents += '<main>{1}</main>'
               bodycontents += '</section>'
               bodycontents = bodycontents.format(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(e[2])), e[1])
 
        elif request == "/fun3":
            # 分析
            # bodycontents += chart_file.format()
            # bodycontents += "<img src='images/DXd_logo1.jpg'>"
            bodycontents += '<div id="my-chart" style="height: 550px;width: 100%;max-width: 800px;margin: 0 auto;">'
            bodycontents += '<table class="charts-css line" id="my-line">'
            bodycontents += '<tbody>'
            
            bodycontents += '<tr>'
            bodycontents += '<th scope="row">い</th>'
            bodycontents += '<td style="--start: 0.8;--size: 0.5;"></td>'
            bodycontents += '</tr>'
            bodycontents += '<tr>'
            bodycontents += '<th scope="row">ろ</th>'
            bodycontents += '<td style="--start: 0.8;--size: 0.5;"></td>'
            bodycontents += '</tr>'
            bodycontents += '<tr>'
            bodycontents += '<th scope="row">は</th>'
            bodycontents += '<td style="--start: 0.8;--size: 0.5;"></td>'
            bodycontents += '</tr>'
            bodycontents += '<tr>'
            bodycontents += '<th scope="row">に</th>'
            bodycontents += '<td style="--start: 0.8;--size: 0.5;"></td>'
            bodycontents += '</tr>'

            # for e in sorted(db.get(), key=lambda e: e[2], reverse=True):
            #     bodycontents += '<tr>'
            #     bodycontents += '<th scope="row"> {0} </th>'
            #     bodycontents += '<td style="--start: 0.8;--size: 0.5;"></td>'
            #     #bodycontents += '<td style="--start: ' + round(random.random(),2) + ';--size: ' + round(random.random(),2) + ';"></td>'
            #     bodycontents += '</tr>'

            bodycontents += '</tbody>'
            bodycontents += '</table>'
            bodycontents += '</div>'

        elif request == "/fun4":
            # 設定
            bodycontents += "<h1>Config</h1>"

        elif request == "/post":
            # 送信
            if not "message" in params:
                bodycontents += "<h1>Invalid Post</h1>"

            else:
                db.post(params["message"])
                bodycontents += '<meta http-equiv="REFRESH" content="3;URL=/fun2"><h1>Post Successed.</h1>'
 
        else:
            bodycontents += "<h1>Invalid Request</h1>"

        response = index_file.format(
            header = 'JIBUN_ANALYSE',
            title = 'ジブンアナライズ',
            content = bodycontents

        )

        return response.encode('utf-8')

# server
if __name__ == "__main__":    
    #httpd = socketserver.TCPServer(('', 8000), http_handler) #どちらでも？
    httpd = http.server.HTTPServer(('', 8000), http_handler)
    httpd.serve_forever()

    #with socketserver.TCPServer(('', 8000),http.server.SimpleHTTPRequestHandler) as httpd:
    #httpd.serve_forever()