#!/usr/bin/env python
# -*- coding: utf_8 -*-
import os
import json
import datetime
import logging
import traceback
from flask import Blueprint, request
from app import config, signalManager
from fullstack.login import Auth
from fullstack.validation import validate_schema
from fullstack.response import ResponseCode, response_result
from schema.download import AddSchema, DeleteSchema, QuerySchema, UpdateSchema, DownloadSchema

logger = logging.getLogger(__name__)

download_api = Blueprint("download_api", __name__, url_prefix="/api/v1/%s/download" % config['NAME'])

@download_api.route("/add", methods=['POST'])
@validate_schema(AddSchema)
@Auth.auth_required
def add():
    try:
        user = request.current_user.get("id")
        isSuccess, message = signalManager.actionAddDownload.emit(user, request.schema_data)
        if isSuccess:
            return response_result(ResponseCode.OK, msg=message)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))


@download_api.route("/delete/<uuid:id>", methods=['POST'])
@validate_schema(DeleteSchema)
@Auth.auth_required
def delete(id):
    try:
        user = request.current_user.get("id")
        isSuccess, message = signalManager.actionDeleteDownload.emit(user, id)
        if isSuccess:
            return response_result(ResponseCode.OK, msg=message)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR)


@download_api.route("/apps", methods=["POST"])
@validate_schema(DownloadSchema)
def get():
    try:
        result, message = signalManager.actionGetDownload.emit(request.schema_data)
        print(message)
        # 读取epk文件，按照格式返回相应结构体数据
        ret = ""
        if isinstance(result, str) and os.path.exists(result):
            with open(result, "rb") as f:
                ret = f.read()
            return ret
        return response_result(ResponseCode.SERVER_ERROR, msg="file not found")
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR, msg=str(e))


@download_api.route("/list", methods=['POST'])
@validate_schema(QuerySchema)
@Auth.auth_required
def get_list():
    try:
        user = request.current_user.get("id")
        result, count, message = signalManager.actionGetDownloadList.emit(user, request.schema_data)
        if result:
            return response_result(ResponseCode.OK, data=result, msg=message, count=count)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR)


@download_api.route("/update/<uuid:id>", methods=['POST'])
@validate_schema(UpdateSchema)
@Auth.auth_required
def update(id):
    try:
        user = request.current_user.get("id")
        isSuccess, message = signalManager.actionUpdateDownload.emit(user, id, request.schema_data)
        if isSuccess:
            return response_result(ResponseCode.OK, msg=message)
        else:
            return response_result(ResponseCode.REQUEST_ERROR, msg=message)
    except Exception as e:
        traceback.print_exc()
        logger.error(str(e))
        return response_result(ResponseCode.SERVER_ERROR)
