# Project#11 - Security Tapes Part#2
# Information - We are going to build on project#6, so don't worry when you see a lot of the same code.
# What are we going to add?  We're going to record video with a webcam when motion from the PIR motion sensors on...
# ... The RPI_no_RPI is detected.  Once detected, the webcam will start taking vide0.  After about ten seconds, the
# Video will close.  It will be saved in the directory that you provide in the code, and the video will be...
# ... time-stamped.  This will loop until you terminate the program.
# If you don't have a webcam, you can purchase some from amazon for very cheap.  I'll be using the default camera...
# ... In my laptop for this video.  Most laptops have cameras built in.

import cv2    # This module is for video recording.  When the red balloon pops up, select the second option from the top
import os     # os comes standard with python, and it will be used to browse and save to directories
import datetime # You know this bad boy by now.  It will be used to timestamp our videos.
import time     # For delays/sleep
import serial   # For RPI_no_RPI communication
from email.message import EmailMessage # included library that assists with sending emails
import ssl # For security when sending emails
import smtplib  # For the actual email sending

try:  # Try to establish communication with the RPInoRPI board.  if successful, only the 'try:' will be executed
    MCU = serial.Serial(port='COM10', baudrate=115200, timeout=0.01)  # Timeout = 0.01.  More on this later.
    time.sleep(5)  # Wait 5 seconds.
except:  # If communication with the RPInoRPI could not be established, then perform the following instead:
    print('System Locked - Cannot communicate with MCU.  Close this program, then reconnect to MCU and restart program')
    while True:  # Forever loop.  Close the program and start again.  Check connection to the RPInoRPI
        pass  # Do nothing

def send_the_email(x):  # This function acts to send the email
    email_sender = 'capnwow123@gmail.com'  # This is my personal email address that I created for this project.
    # You will need to use the video linked above in this code to make your own email address compatible with python
    email_password = 'qumuseakvnxxxxh'      # This is my password.  You'll need to add your own here with quotations
    email_receiver = 'pat@hotmail.com'  # This is the email address that you'll be sending to.
    subject = 'Motion has been detected'  # This is the subject line body
    body = "Motion has been detected and video was taken at: " + str(x)  # The body of the email
    email = EmailMessage()        # The following lines of code set up the email and send it
    email['From'] = email_sender
    email['To'] = email_receiver
    email['Subject'] = subject
    email.set_content(body)       # Just a required command

    context = ssl.create_default_context()  # add in security

    with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:  # Get ready to send the email
        smtp.login(email_sender, email_password)                            # Login
        smtp.sendmail(email_sender, email_receiver, email.as_string())      # Send the email

cap= cv2.VideoCapture(0)  # Use the default laptop camera (0)
# IF you have more than one camera plugged in, you should be able to select 0 or 1.  If you have even more, 0/1/2
# Most webcams available on amazon are compatible with cv2, but if you have a laptop, stick to the laptop camera
# Below you  set the frame width and height of the video.  This is just a requirement of the module
width= int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))   # Set up the width and height of the viewer
height= int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

while True:  # Execute the following forever until you stop the program
    data = MCU.readline()  # Wait for a response from the MCU, and store the returned value in 'data
    data = str(data)       # The value in 'data' should already be a string, but change it into a string anyway.
    # If you want to verify the type of data in a variable, you can do this: print(type(data))
    # print(data)   # If you want, you can print the value of 'data' in the shell if you comment this back in.
    # print(type(data)) # Also, print the type if you'd like
    if data == "b'5'":
        writer = cv2.VideoWriter('C:/Reports/Videos/basicvideo.mp4', cv2.VideoWriter_fourcc(*'mp4v'), 20,(width, height))
        # Name the video.  We will rename it later.  We need to save the video now as baseline 'basicvideo.mp4'
        # We'll re-save it later as a timestamp.
        counter = 0                # For auto exiting of a loop
        while True:                # Do the following until 'break'
            ret,frame= cap.read()  # Read the camera
            writer.write(frame)    # Save the video
            counter = counter + 1  # When counter = 100, end this loop
            #print(counter)         # When you're done with this, you can delete it.
            if counter == 200:     # Do nothing until counter = 200.  This acts as a delay.
                break              # End the loop
        writer.release()           # Close the video file
        cv2.destroyAllWindows()    # Terminate OS stuff
        # At this point the video is saved.  Now we need to rename it.  We rename it for two reasons.
        # The first reason is that the original basicvideo name will be overwritten each time a video is recorded if you...
        # ... don't rename it.  The second is that you get to ACCURATELY date-stamp the video, so that you know when the...
        # ... video was taken.
        filename = str(datetime.datetime.now().strftime("%Y-%mm-%dd-%Hh-%Mm-%Ss"))   # Datestamp the failure for new filename
        print("New file name: " + filename)  # Print the new file name so that you can see what it will be
        old_name = r"C:/Reports/Videos/basicvideo.mp4"  # The old name of the video file that we just took
        dst = 'C:/Reports/Videos/' + filename + '.mp4'  # The new name of the file (Date-stamped)  dst = date-stamped
        os.rename(old_name, dst)                        # Rename the file with the newly date-stamped name
        print('Motion detected at' + filename)          # Print this + the date-stamp to the shell (if you want)
        send_the_email(filename)   # Send the email with the filename date-stamp by calling send_the_email
        time.sleep(10)             # Wait 10 seconds before starting the loop again