# -*- coding: utf-8 -*-
from bottle import route, run, template, static_file,url,request
from janome.tokenizer import Tokenizer
from collections import Counter
import os
import re
import word_match

# read "css","javascript"
@route('/static/<filepath:path>',name='static_file')
def static(filepath):
    return static_file(filepath, root='./static')

@route('/<filepath:path>', name='static_file')
def static(filepath):
    return static_file(filepath, root="./view/")


@route('/')
def index():
    # Logic
    return template("index",url=url)

@route('/upload', method='POST')
def do_upload():
    p = re.compile(r'\s(.*)')
    category   = request.forms.get('category')
    upload     = request.files.get('upload')
    name, ext = os.path.splitext(upload.filename)
    if ext not in ('.csv','.json','.txt'):
        return 'File extension not allowed.'
    
    save_path = get_save_path_for_category(category)
    upload.save(save_path,True) # appends upload.filename automatically

    analyzed_file = str(save_path) + str(upload.filename)

    result_file_path = do_analysis(analyzed_file)

    with open(result_file_path,mode='r', encoding='utf-8') as read_file:
        texts = read_file.readlines()

    counter = Counter(texts)
    word_count = []
#    total_count = []
    for word,cnt in counter.most_common():


        check_word = p.sub('',word)
        
        if word_match.word_check(check_word):
            continue


        word_count.append(str(p.sub('',word)) + " : " + str(cnt))
#        total_count.append(cnt)


#   total_count = sum([cnt])
    return template("result",url=url, result_file=result_file_path,result_text=texts,word_count = word_count)



# create a filepath of result file
def get_save_path_for_category(category):
    if category == '':
        return "./"
    return "tmp/" + str(category) + "/"

def do_analysis(analyzed_file):
    result_file_name = "result/" + str(analyzed_file)

    p = re.compile(r'\s(.*)')

    t = Tokenizer()
    
    with open(analyzed_file,mode='r', encoding='utf-8') as read_file:
        texts = read_file.read()
    
    with open(result_file_name, mode='a', encoding='utf-8') as result_file:
        for token in t.tokenize(str(texts)):
            check_word = p.sub('',str(token))
            if not word_match.word_check(check_word):
                result_file.write(str(token) + "\n")
        
    return result_file_name



# サーバーの設定(開発用) - debugとreloaderを有効にしている
run(host='localhost', port=8081, debug=True, reloader=True)
@@ -2407,45 +2407,65 @@
 %0A%0A# 
-%E3%82%B5%E3%83%BC%E3%83%90%E3%83%BC%E3%81%AE%E8%A8%AD%E5%AE%9A(%E9%96%8B%E7%99%BA%E7%94%A8) - debug%E3%81%A8reloader%E3%82%92%E6%9C%89%E5%8A%B9%E3%81%AB%E3%81%97%E3%81%A6%E3%81%84%E3%82%8B
+Server setting - Develop -%3E Enable to debug and reloader.
 %0Arun

Update a source code comment.