import cv2
import argparse
from ultralytics import YOLO
import supervision as sv
import numpy as np
import requests
import time
import os

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from pathlib import Path
import smtplib

ZONE_POLYGON = np.array([
    [0, 0],
    [0.3, 0],
    [0.3, 1],
    [0, 1]
])


def parse_arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="YOLOv8 live")
    parser.add_argument(
        "--webcam-resolution",
        default=[800, 600],
        nargs=2,
        type=int
    )
    args = parser.parse_args()
    return args

# 修改為你要傳送的訊息內容
msg = '偵測到：'
# 修改為你的權杖內容
token = 'fDzzBZtLGAukpn7BATssNcB2zbkUajyoHMSQh0IgfT4'
def lineNotifyMessage(token,msg):
    headers = {
        "Authorization": "Bearer " + token
    }
    payload = {'message': msg}
    image = open('result.jpg','rb')
    #files = { 'imageFile': image }

    #r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=payload, files = files)
    r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=payload)
    print(r.text)
    return r.status_code




def main():
    args = parse_arguments()
    frame_width, frame_height = args.webcam_resolution
    #print(frame_width,frame_height)
    cap = cv2.VideoCapture(0)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, frame_width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_height)

    #model = YOLO("yolov8n.pt")
    model = YOLO("best.pt")

    box_annotator = sv.BoxAnnotator(
        thickness=2,
        text_thickness=2,
        text_scale=1
    )

    zone_polygon = (ZONE_POLYGON * np.array(args.webcam_resolution)).astype(int)
    zone = sv.PolygonZone(polygon=zone_polygon, frame_resolution_wh=tuple(args.webcam_resolution))
    zone_annotator = sv.PolygonZoneAnnotator(
        zone=zone,
        color=sv.Color.blue(),
        thickness=2,
        text_thickness=4,
        text_scale=2
    )
    count = 0

    while True:
        ret, frame = cap.read()
        result = model(frame, agnostic_nms=True)[0]
        detections = sv.Detections.from_yolov8(result)

        labels = [
            f"{model.model.names[class_id]} {confidence:0.2f}"
            for _, confidence, class_id, _
            in detections
        ]

        labels_name = [
            f"{model.model.names[class_id]}"
            for _, confidence, class_id, _
            in detections
        ]

        labels_confidence = [
            f"{confidence:0.2f}"
            for _, confidence, class_id, _
            in detections
        ]

        frame = box_annotator.annotate(
            scene=frame,
            detections=detections,
            labels=labels
        )
        #print('name',labels_name)
        # print('confidence', labels_confidence)
        if labels_name == 0:
            continue
        elif labels_name == ['Fatwolf']:
            count = count+1
            now_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
            get_labels_name = ''.join(filter(str.isalpha,labels_name))
            save_picpath = "./"+get_labels_name
            if not os.path.isdir(save_picpath):
                os.makedirs(save_picpath)
            cv2.imwrite('result.jpg',frame)
            write_image = now_time + '_' + str(count) + '.jpg'
            cv2.imwrite(save_picpath+'/'+write_image, frame)
            lineNotifyMessage(token, (msg+get_labels_name))

            message = MIMEMultipart()
            message["from"] = "qwe03160825@gmail.com"
            message["to"] = "service.gitcr081@gmail.com"
            message["subject"] = "[警告訊息]偵測到不明人士!"
            now_time = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime(time.time()))
            #image = 'result.jpg'
            message.attach(MIMEText("時間：" + now_time + "\n偵測到不明人士"))
            #message.attach(MIMEImage(Path(image).read_bytes()))
            with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
                smtp.ehlo()
                smtp.starttls()
                smtp.login("qwe03160825@gmail.com", "jbroyqabjqdscujo")
                smtp.send_message(message)
                print("sent...")

        # zone.trigger(detections=detections)
        # frame = zone_annotator.annotate(scene=frame)
        cv2.imshow("yolov8", frame)

        key = cv2.waitKey(1)
        if key == ord('q'):
            break


if __name__ == "__main__":
    main()
    