from flask import Flask,send_from_directory
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from flasgger import Swagger


def warn(*args, **kwargs):
    pass
import warnings
warnings.warn = warn


app = Flask(__name__)
Swagger(app)

api = Api(app)
import os
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'some-secret-string'
app.config['UPLOAD_FOLDER'] = 'tmp/upload'
app.config['DOWNLOAD_PATH'] = os.path.abspath('./docs')
app.config['JSON_AS_ASCII'] = False
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
db = SQLAlchemy(app)

app.config['JWT_SECRET_KEY'] = 'jwt-secret-string'
jwt = JWTManager(app)

app.config['JWT_BLACKLIST_ENABLED'] = True
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access', 'refresh']
@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
    jti = decrypted_token['jti']
    return models.RevokedTokenModel.is_jti_blacklisted(jti)


import views, models, resources

api.add_resource(resources.Whois,'/whois')
@app.route('/whois/', methods=['POST'])
def whois_info():
    """
    人臉辨識
    ---
    tags:
      - 人臉辨識回傳結果
    description:
        人臉辨識接口，img file格式
    parameters:
      - name: body
        in: body
        required: true
        schema:
          id: 人臉辨識
          required:
            - file
          properties:
            file:
              type: image/jpeg
              description: 預辨識照片.

    responses:
      201:
          description: 辨識成功


          example: { "time": 1561950037.7547767,"face_location": "[[125   7 270 270]]","uid":["RD10502"],"name": "李宗翰","confidence": [0.2725946425242175]}
      406:
        description: 偵測不到人臉請重新調整
    """
    pass
api.add_resource(resources.Upload_image,'/upload/image')
@app.route('/upload/image', methods=['POST'])
def upload_image_info():
    """
    上傳訓練樣本
    ---
    tags:
      - 上傳訓練樣本
    description:
        上傳訓練樣本，img file格式
    parameters:
      - name: body
        in: body
        required: true
        schema:
          id: 上傳訓練樣本
          required:
            - uid
            - file
          properties:
            uid:
              type: string
              description: 預訓練人員id.
            file:
              type: image/jpeg
              description: 預訓練照片.

    responses:
      201:
          description: 上傳成功

          example: { "message": "test已新增訓練樣本" }
      406:
        description: 偵測不到人臉 請重新上傳
    """
    pass
api.add_resource(resources.Train,'/train')
@app.route('/train', methods=['GET'])
def train_info():
    """
    上傳訓練樣本
    ---
    tags:
      - 開始訓練
    description:
        開始自動加載訓練新模型
    responses:
      201:
          description: 訓練完成

          example: { "message": "訓練完成" }
      406:
        description: 樣本錯誤請重新檢查
    """
    pass
api.add_resource(resources.Clock,'/clock')
@app.route('/clock', methods=['POST'])
def clock_info():
    """
    開始打卡
    ---
    tags:
      - 開始打卡
    description:
        上下班打卡，寫入資料庫並儲存至Nas
    parameters:
      - name: body
        in: body
        required: true
        schema:
          id: 開始打卡
          required:
            - time
            - uid
            - log
            - status
          properties:
            time:
              type: float
              description: 打卡時間戳記.
            uid:
              type: string
              description: 人員id.
            log:
              type: string
              description: 上班或下班.
            status:
              type: string
              description: 辨識成功或失敗.

    responses:
      201:
          description: 上班(下班)打卡成功

          example: { "message": "Bruce打卡成功" }
      406:
        description: 輸入格式錯誤
    """
    pass

api.add_resource(resources.Insert_employee,'/insert')
@app.route('/insert', methods=['POST'])
def insert_info():
    """
    新增人員資料
    ---
    tags:
      - 新增人員資料
    description:
        新增人員到資料庫，以供後續訓練
    parameters:
      - name: body
        in: body
        required: true
        schema:
          id: 新增人員
          required:
            - name
            - engname
            - phone
            - years
          properties:
            name:
              type: string
              description: 預新增人員人員姓名.
            engname:
              type: string
              description: 預新增人員英文名.
            phone:
              type: string
              description: 手機號碼.
            years:
              type: string
              description: 入學年或職稱代碼以供編號.

    responses:
      201:
          description: 新增成功

          example: { "message": "Bruce新增成功" }
      406:
        description: 輸入格式錯誤
    """
    pass
api.add_resource(resources.Report,'/report/<file_type>/<int:year>/<int:month>/<uid>')
@app.route('/report', methods=['GET'])
def report_info():
    """
    產生報表
    ---
    tags:
      - 產生報表
    description:
        產生出勤報表以供人事審查
    parameters:
      - name: body
        in: body
        required: true
        schema:
          id: 產生報表
          required:
            - file_type
            - year
            - month
            - uid
          properties:
            file_type:
              type: string
              description: 產生excel或json格式報表.
            year:
              type: int
              description: 預查詢之年度.
            month:
              type: int
              description: 預查詢之月份.
            uid:
              type: string
              description: 預查詢之員工標號.

    responses:
      201:
          description: 查詢成功產生報表

          example: {
  "log": {
    "2019-07-01": {
      "login": "08:21:52", 
      "logout": "17:53:55", 
      "overtime": 0.5
    }, 
    "2019-07-02": {
      "login": "08:13:44", 
      "logout": "17:34:27", 
      "overtime": 0
    }
  }, 
  "name": "李宗翰", 
  "range": "2019年7月"
}
      406:
        description: 查詢錯誤請重新輸入
    """
    pass
@app.route('/download/<filename>')
def download_zh_file(filename):
    path = app.config['DOWNLOAD_PATH']
#     filename = 'Allen7月出勤紀錄.xlsx'
    return send_from_directory(path, filename)

# @app.route("/docs/<fname>", methods=['GET'])
# def download_file(fname):
#     MyFolder=os.path.abspath('./docs')
#     # 此處的filepath是檔案的路徑，但是檔案必須儲存在static資料夾下， 比如images\test.jpg
#     return send_from_directory(MyFolder, fname, mimetype='application/octet-stream') 

@app.before_first_request
def create_tables():
    db.create_all()

if __name__ == '__main__':
#     print(('* Loading Keras model and Flask starting server...'
#         'please wait until server has fully started'))
#     perload_model()
    app.run()
    
# app.run(host='0.0.0.0', port=8000, debug=True)