from flask import request, jsonify, send_file
from flask_api import status
from flask_restful import Resource, reqparse
import os, sys
sys.path.append(os.path.join('./', 'models'))
sys.path.append(os.path.join('./', 'static'))
sys.path.append(os.path.join('./', 'resources', 'test'))

from influx_model import BaseInfluxModel, LogInfluxModel
influx = BaseInfluxModel()

# ========== 基礎資源 ==========
class BaseResource(Resource):
    def __init__(self, model="unknown"):
        self.parser = reqparse.RequestParser()
        self.log = LogInfluxModel(model)
        self.log.SetHost(request.remote_addr)
        self.code = status.HTTP_200_OK
        self.message = ""
        self.data = None
        self.result = 1
    def GetResponse(self, user="unknown"):
        self.log.SetUser(user)
        self.log.SetCode(self.code)
        self.log.SetMessage(self.message)
        response = jsonify(self.log.GetMessage(self.data, self.result))
        response.status_code = self.code
        influx.Add(self.log)
        influx.Upload()
        return response
# ========== base file resource ==========
class SendBaseResource(BaseResource):
    def __init__(self, fileType):
        super().__init__()
        self.parser = reqparse.RequestParser()
        self.type = fileType
    def GetFileResponse(self, file):
        if os.path.isfile(file):
            return send_file(file, self.type)
        else:
            self.message = "File {0} isn't exist".format(file)
            return self.GetResponse()
    def GetExcelResponse(self, name, stream):
        return send_file(stream, attachment_filename="{0}.xlsx".format(name), as_attachment=True)
    def GetWordResponse(self, name, stream):
        return send_file(stream, attachment_filename="{0}.docx".format(name), as_attachment=True)
    def GetTxtResponse(self, name, stream):
        return send_file(stream, attachment_filename="{0}.txt".format(name), as_attachment=True)