from flask import Blueprint, render_template, redirect,request,jsonify
from app import app
from app import sched, trigger
from app.etlMongo.pubFunction import set_log
from app.etlMongo.tabStudent import get_stu_info
from app.etlMongo.tabHomework import get_homework
from app.etlMongo.tabGame import get_game_info
from . import shellPy
import datetime
import time

getEtl = Blueprint('getEtl', __name__)


def getTraceId():
    import uuid
    return str(uuid.uuid1()).replace('-', '')


@getEtl.route('/etlTest/gettest', methods=['GET'])
def etl_test():
    # print('aaaTestNow is %s' % datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    datas = {'msg': 'Successful!'}
    return jsonify(datas)


@getEtl.route('/etlStudent', methods=['GET'])
def etl_student():
    password = request.values.get('password')
    start_time = time.time()
    if password == 'bigdata123':
        get_stu_info()
        code = 200
        datas = {'msg': 'Succeed to import table of student!', 'code': code}
    else:
        code = 400
        datas = {'msg': 'Error, Password was wrong!', 'code': code}
    end_time = time.time()
    finish_time = end_time - start_time
    set_log('etlStudent-', str(code) + ':' + str(finish_time))
    return jsonify(datas)


@getEtl.route('/etlHomework', methods=['GET'])
def etl_homework():
    password = request.values.get('password')
    start_time = time.time()
    if password == 'bigdata123':
        get_homework()
        code = 200
        datas = {'msg': 'Succeed to import table of homework!', 'code': code}
    else:
        code = 400
        datas = {'msg': 'Error, Password was wrong!', 'code': code}
    end_time = time.time()
    finish_time = end_time - start_time
    set_log('etlHomework-', str(code) + ':' + str(finish_time))
    return jsonify(datas)


@getEtl.route('/etlGame', methods=['GET'])
def etl_game():
    password = request.values.get('password')
    start_time = time.time()
    if password == 'bigdata123':
        get_game_info()
        code = 200
        datas = {'msg': 'Succeed to import table of game!', 'code': code}
    else:
        code = 400
        datas = {'msg': 'Error, Password was wrong!', 'code': code}
    end_time = time.time()
    finish_time = end_time - start_time
    set_log('etlGame-', str(code) + ':' + str(finish_time))
    return jsonify(datas)


@sched.scheduled_job(trigger)
def on_time_etl():
    start_time = time.time()

    shellPy.local_shell_ext(shellPy.local_mv_command)  # 先执行本地MV命令
    get_stu_info()
    get_homework()
    get_game_info()
    etl_result = shellPy.data_etl_ext()

    end_time = time.time()
    finish_time = end_time - start_time
    log_info = 'Code[' + str(etl_result) + ']TimeCost[' + str(finish_time) + ']'
    set_log('etlAutoTable-', log_info)
