# coding: utf-8

import os
from whoosh.index import create_in, exists_in
from whoosh.fields import TEXT, DATETIME, NUMERIC, SchemaClass
from decouple import config


INDEX_FOLDER_PATH = config('LOG_INDEX_PATH')


class AccessLog(SchemaClass):
    ip = TEXT(stored=True)
    time = DATETIME(stored=True)
    host = TEXT(stored=True)
    args = TEXT(stored=True)
    status = TEXT(stored=True)
    ua = TEXT(stored=True)
    uri = TEXT(stored=True)
    method = TEXT(stored=True)
    refer = TEXT(stored=True)
    flag = NUMERIC(stored=True)
    location = TEXT(stored=True)


def create_index():
    file_name = INDEX_FOLDER_PATH
    if not os.path.isdir(file_name):
        print 'no such folder, program is creating this folder.'
        try:
            os.mkdir(file_name)
            print 'folder created.'
        except Exception as e:
            print 'create folder failed: {}'.format(e)
    if exists_in(file_name):
        print 'index already exists, nothing changed.'
    else:
        ix = create_in(file_name, AccessLog)
        print 'index created.'
        return True


if __name__ == '__main__':
    create_index()
