   #imports
from gpiozero import Button
import time
import RPi.GPIO as GPIO
from picamera2 import Picamera2
import cv2
import numpy as np
from escpos.printer import File
from PIL import Image
import os
import subprocess

os.environ['ALSA_CARD'] = '1'

time.sleep(3)

#button
button = Button(4)

#motor
in1 = 24
in2 = 23
en = 25

GPIO.setmode(GPIO.BCM)
GPIO.setup(in1, GPIO.OUT)
GPIO.setup(in2, GPIO.OUT)
GPIO.setup(en, GPIO.OUT)
GPIO.output(in1, GPIO.LOW)
GPIO.output(in2, GPIO.LOW)
p = GPIO.PWM(en, 0.5)
p.start(25)

#video
picam2 = Picamera2()
picam2.start()

#printer
printer = File("/dev/usb/lp0")
printer._raw(b'\x1B\x40')

def takeAndPrintPhoto():
    print("taking photo")
    #take and save photo
    frame = picam2.capture_array()
    frame = frame[:, :, [2,1,0]]
    cv2.imwrite("frame.jpg", frame)

    #print photo
    print("printing photo")
    img = Image.open("frame.jpg").convert("L")
    width = 380
    img = img.rotate(90, expand=True)
    img = img.resize((width, int(img.height * width / img.width)))
    printer._raw(b'\x1B\x37' + bytes([10, 60, 4]))
    printer.image(img)
    printer._raw(b'\x1B\x64\x08')

def playAudio():
    print("playing noise")
    subprocess.run(["aplay", "/home/pi/Downloads/scream.wav"])
    time.sleep(0.1)

def extendGhost():
    GPIO.output(in1, GPIO.LOW)
    GPIO.output(in2, GPIO.HIGH)
    print("extending ghost")

def stopMotor():
    GPIO.output(in1, GPIO.LOW)
    GPIO.output(in2, GPIO.LOW)

def retractGhost():
    GPIO.output(in1, GPIO.HIGH)
    GPIO.output(in2, GPIO.LOW)
    print("retracting ghost")
    time.sleep(2)

def main():
    print("main entered")
    extendGhost()
    playAudio()
    takeAndPrintPhoto()
    retractGhost()
    stopMotor()

playAudio()
while True:
    if button.is_pressed:
        main()