#!/usr/bin/env python
# -*- coding:utf-8 -*-
from whoosh.filedb.filestore import FileStorage
from whoosh import index
from whoosh.index import FileIndex
from whoosh.fields import Schema, ID, TEXT
from whoosh.writing import AsyncWriter
import pymysql
from decimal import Decimal
from common.base import MyPymysql


def my_add_document(mykeys, row, writer):
    tables = ["meta_project", "meta_questionnaire", "meta_variable"]
    projKey = []
    quesKey = []
    varKey = []
    dataBase = "db_metadata"
    ret = MyPymysql('notdbMysql')
    for i in range(len(tables)):
        if tables[i] == "meta_project":
            ProjectSql = "select COLUMN_NAME as columnName from information_schema.COLUMNS where table_name = '{}' and table_schema = '{}';".format(
                tables[i],
                dataBase)

            ProjectColumnName = ret.selectall_sql(ProjectSql)
            for j in ProjectColumnName:
                projKey.append(j["columnName"])
        elif tables[i] == "meta_variable":
            VariableSql = "select COLUMN_NAME as columnName from information_schema.COLUMNS where table_name = '{}' and table_schema = '{}';".format(
                tables[i],
                dataBase)

            VariableColumnName = ret.selectall_sql(VariableSql)
            for j in VariableColumnName:
                varKey.append(j["columnName"])
        elif tables[i] == "meta_questionnaire":
            QuesSql = "select COLUMN_NAME as columnName from information_schema.COLUMNS where table_name = '{}' and table_schema = '{}';".format(
                tables[i],
                dataBase)

            QuesColumnName = ret.selectall_sql(QuesSql)
            for j in QuesColumnName:
                quesKey.append(j["columnName"])
    ret.close()

    docline = """writer.add_document("""
    if mykeys == 1:
        mykeys = projKey
    elif mykeys == 2:
        mykeys = quesKey
    elif mykeys == 3:
        mykeys = varKey

    for key in mykeys:
        val = row[key]
        if not val:
            val = ""
        elif isinstance(val, (Decimal,)):
            val = str(val)
        else:
            val = pymysql.escape_string(str(val))
        docline += key + '="' + val + '", '
    docline = docline.rstrip(", ")
    docline += """)"""
    eval(docline)


def incremental_index(indexdir, indexname):
    storage = FileStorage(indexdir)
    ix = FileIndex(storage, indexname=indexname)
    writer = AsyncWriter(ix)
    return writer


def myCommit(writer):
    writer.commit()


if __name__ == '__main__':
    indexname = "metaproject"
    indexdir = "indexdir"
    mykeys = 1
    row = {}
    writer = incremental_index(indexdir, indexname)
    my_add_document(mykeys, row, writer)
    myCommit(writer)
