from flask import request, jsonify, send_file
from flask_api import status
from flask_restful import Resource, reqparse
import os, sys
import json
from datetime import datetime,timedelta


sys.path.append(os.path.join('./', 'models'))
sys.path.append(os.path.join('./', 'static'))
from influx_model import BaseInfluxModel, LogInfluxModel
from mysql_model import PersonModel,PersonGroupRelationModel,PersonModel
from punch_card_resource import PunchCardRecord

# 基本回應測試連線使用
class Grafana_Base(Resource):
    def __init__(self):
        super().__init__()
    def get(self):
        return 'work'
# 資料搜尋
class Grafana_Query(Resource):
    def __init__(self):
        super().__init__()
        self.log = LogInfluxModel("Grafana Query")
        self.inHour=8
        self.inMinute=30
        self.outHour=17
        self.outMinute=30
        self.lunchBreak=60
    def get_late_record(self,dt_from,dt_to):
        # Get person data
        person = PersonModel.AllFromDB(self.log)
        # strart end 格式 yyyy-MM-dd HH:mm:ss datetime object
        # 取得區間紀錄
        record = PunchCardRecord.GetTable(dt_from, dt_to, person)
       
        json_data=[]

        for ID,p in zip(record.keys(),person):
            late_data={
                "target":p.GetName(),
                "datapoints":[]
            }
            for dateString in record[ID].keys():

                i1 = datetime.strptime(dateString, '%Y-%m-%d')
                i1 = i1 + timedelta(hours=12)
                i2 = record[ID][dateString]['Start']['Time']
                i2 = "{0} {1}".format(dateString, i2)
                i2 = datetime.strptime(i2, '%Y-%m-%d %H:%M:%S')
                i3 = record[ID][dateString]['End']['Time']
                i3 = "{0} {1}".format(dateString, i3)
                i3 = datetime.strptime(i3, '%Y-%m-%d %H:%M:%S')
                i4 = self.inHour
                i5 = self.inMinute
                i6 = self.outHour
                i7 = self.outMinute
                i8 = self.lunchBreak
                # start, end, startOver, endOver, work, over
                o1, o2, o3, o4, o5, o6 = PunchCardRecord.CalculateTime(i1, i2, i3, i4, i5, i6, i7, i8, 10, 15)
                # ------- 2020 08 07 Allen 新增備註，標記遲到早退 --------
                late = datetime(i1.year, i1.month, i1.day, self.inHour, self.inMinute+1)
                late = (i2 - late).total_seconds() if i2 > late else 0
                earlier = datetime(i1.year, i1.month, i1.day, self.outHour, self.outMinute)
                earlier = (earlier - i3).total_seconds() if earlier > i3 else 0
                note=""
                if(late > 0):
                    # 遲到
                    late_data['datapoints'].append([late/3600,int(o1.timestamp()*1000)])
            if(len(late_data['datapoints'])>0):
                json_data.append(late_data)
        return json_data
    def get_over_record(self,dt_from,dt_to):
        # Get person data
        person = PersonModel.AllFromDB(self.log)
        # strart end 格式 yyyy-MM-dd HH:mm:ss datetime object
        # 取得區間紀錄
        record = PunchCardRecord.GetTable(dt_from, dt_to, person)
        
        json_data=[]

        for ID,p in zip(record.keys(),person):
            late_data={
                "target":p.GetName(),
                "datapoints":[]
            }
            for dateString in record[ID].keys():

                i1 = datetime.strptime(dateString, '%Y-%m-%d')
                i1 = i1 + timedelta(hours=12)
                i2 = record[ID][dateString]['Start']['Time']
                i2 = "{0} {1}".format(dateString, i2)
                i2 = datetime.strptime(i2, '%Y-%m-%d %H:%M:%S')
                i3 = record[ID][dateString]['End']['Time']
                i3 = "{0} {1}".format(dateString, i3)
                i3 = datetime.strptime(i3, '%Y-%m-%d %H:%M:%S')
                i4 = self.inHour
                i5 = self.inMinute
                i6 = self.outHour
                i7 = self.outMinute
                i8 = self.lunchBreak
                # start, end, startOver, endOver, work, over
                o1, o2, o3, o4, o5, o6 = PunchCardRecord.CalculateTime(i1, i2, i3, i4, i5, i6, i7, i8, 10, 15)
                # ------- 2020 08 07 Allen 新增備註，標記遲到早退 --------
                late = datetime(i1.year, i1.month, i1.day, self.inHour, self.inMinute+1)
                late = (i2 - late).total_seconds() if i2 > late else 0
                earlier = datetime(i1.year, i1.month, i1.day, self.outHour, self.outMinute)
                earlier = (earlier - i3).total_seconds() if earlier > i3 else 0
                note=""
                if(o6 > 0):
                    # 加班
                    late_data['datapoints'].append([o6,int(o2.timestamp()*1000)])
            if(len(late_data['datapoints'])>0):
                json_data.append(late_data)
        return json_data
    def get_attendance_record_table(self,dt_from,dt_to):
        # Get person data
        person = PersonModel.AllFromDB(self.log)
        # strart end 格式 yyyy-MM-dd HH:mm:ss datetime object
        # 取得區間紀錄
        record = PunchCardRecord.GetTable(dt_from, dt_to, person)
        json_data=[{
            "columns":[
                {"text":"姓名","type":"string"},
                {"text":"遲到","type":"number"},
                {"text":"加班","type":"number"},
                {"text":"早退","type":"number"}
            ],
            "rows":[],
            "type":"table" }]

        for ID,p in zip(record.keys(),person):
            # 姓名 遲到 早退 加班  (次數)
            data=[p.GetName(),0,0,0]
            for dateString in record[ID].keys():

                i1 = datetime.strptime(dateString, '%Y-%m-%d')
                i1 = i1 + timedelta(hours=12)
                i2 = record[ID][dateString]['Start']['Time']
                i2 = "{0} {1}".format(dateString, i2)
                i2 = datetime.strptime(i2, '%Y-%m-%d %H:%M:%S')
                i3 = record[ID][dateString]['End']['Time']
                i3 = "{0} {1}".format(dateString, i3)
                i3 = datetime.strptime(i3, '%Y-%m-%d %H:%M:%S')
                i4 = self.inHour
                i5 = self.inMinute
                i6 = self.outHour
                i7 = self.outMinute
                i8 = self.lunchBreak
                # start, end, startOver, endOver, work, over
                o1, o2, o3, o4, o5, o6 = PunchCardRecord.CalculateTime(i1, i2, i3, i4, i5, i6, i7, i8, 10, 15)
                # ------- 2020 08 07 Allen 新增備註，標記遲到早退 --------
                late = datetime(i1.year, i1.month, i1.day, self.inHour, self.inMinute+1)
                late = (i2 - late).total_seconds() if i2 > late else 0
                earlier = datetime(i1.year, i1.month, i1.day, self.outHour, self.outMinute)
                earlier = (earlier - i3).total_seconds() if earlier > i3 else 0
                note=""
                if(late > 0):
                    # 遲到
                    data[1]+=1
                if(earlier > 0):
                    # 早退
                    data[2]+=1
                if(o6 > 0):
                    # 加班
                    data[3]+=1
            json_data[0]['rows'].append(data)
        return json_data
    def get_unrecord_table(self,dt_from,dt_to):
        # Get person data
        person = PersonModel.AllFromDB(self.log)
        # strart end 格式 yyyy-MM-dd HH:mm:ss datetime object
        # 取得區間紀錄
        record = PunchCardRecord.GetFullTable(dt_from, dt_to,self.inHour,self.inMinute,self.outHour,self.outMinute,self.lunchBreak, person)
        json_data=[{
            "columns":[
                {"text":"日期","type":"string"},
                {"text":"姓名","type":"string"},
                {"text":"備註","type":"string"},
            ],
            "rows":[],
            "type":"table" }]
        for key,p in zip(record.keys(),person):
            for dt in record[key].keys():
                if(record[key][dt]['Start']['Time']==''):
                    # 未出席
                    json_data[0]["rows"].append([dt,p.GetName(),""])
        
        return json_data
    def get_group_unrecord_table(self,dt_from,dt_to,group_id):
        # Get person data
        person_group_relation_models=PersonGroupRelationModel.AllPersonFromDB(group_id,self.log)
        persons=[]
        for model in person_group_relation_models:
            person=PersonModel.FromDB(model.GetPersonID(),self.log)
            if(person.isExist):
                persons.append(person)
        # strart end 格式 yyyy-MM-dd HH:mm:ss datetime object
        # 取得區間紀錄
        record = PunchCardRecord.GetFullTable(dt_from, dt_to,self.inHour,self.inMinute,self.outHour,self.outMinute,self.lunchBreak, persons)
        json_data=[{
            "columns":[
                {"text":"日期","type":"string"},
                {"text":"姓名","type":"string"},
                {"text":"備註","type":"string"},
            ],
            "rows":[],
            "type":"table" }]
        for key,p in zip(record.keys(),persons):
            for dt in record[key].keys():
                if(record[key][dt]['Start']['Time']==''):
                    # 未出席
                    json_data[0]["rows"].append([dt,p.GetName(),""])
        
        return json_data
    def post(self):
        request_data=request.data
        json_data=json.loads(request_data.decode('utf-8'))
#         print(json_data)
        dt_from=datetime.strptime(json_data['range']['from'], "%Y-%m-%dT%H:%M:%S.%fZ")+ timedelta(hours=8)
        dt_to=datetime.strptime(json_data['range']['to'], "%Y-%m-%dT%H:%M:%S.%fZ")+ timedelta(hours=8)
#         print(dt_from,dt_to)
        targets=json_data["targets"]
        response_data=[]
        for target in targets:
            if(target['target'] == "區間統計"):
                response_data.extend(self.get_attendance_record_table(dt_from,dt_to))
            elif(target['target'] == "遲到"):
                response_data.extend(self.get_late_record(dt_from,dt_to))
            elif(target['target'] == "加班"):
                response_data.extend(self.get_over_record(dt_from,dt_to))
            elif(target['target'] == "未出席"):
                response_data.extend(self.get_unrecord_table(dt_from,dt_to))
        
        return response_data
# 提示用戶訊息    
class Grafana_Search(Resource):
    def __init__(self):
        super().__init__()
    def post(self):
        request_data=request.data
        # 顯示已實作方法
        return ['區間統計','遲到','加班','早退','未出席']
    
# 獲取標籤 key
# 未實作
class Grafana_Tag_Key(Resource):
    def __init__(self):
        super().__init__()
    def post(self):
        request_data=request.data
#         print(request_data)
        response_data=[
    {"type":"string","text":"City"},
    {"type":"string","text":"Country"}
]
        return response_data
# 獲取標籤 value
# 未實作
class Grafana_Tag_Value(Resource):
    def __init__(self):
        super().__init__()
    def post(self):
        request_data=request.data
#         print(request_data)
        response_data=[
    {"text": "Eins!"},
    {"text": "Zwei"},
    {"text": "Drei!"}
]
        return response_data 