from picamera2 import Picamera2
import cv2

'''
This class represents the camera for the Sudoku project
'''
class SCamera:
    
    def __init__(self):
        """
        Initializes the real camera.

        NOTE: The underlying Picamera code spits out a bunch of INFO
        and WARN messages. The few references I can find suggest
        they all can be safely ignored. The camera does work.
        """
        self.cam = Picamera2()
        camera_config = self.cam.create_still_configuration(main={"size": (3280, 2464), "format": "RGB888"})
        self.cam.configure(camera_config)
                
        self.cam.start()

    def take_photo(self, full=True, debug=False):
        """
        Takes a photo; assumes the iPad is positioned properly.
        Crops the photo to contain only the puzzle or portion.
        :param full: when true, crops for entire puzzle, else partial puzzle
        :param debug: when true will write files containing original and cropped images
        :return: puzzle photo
        """
        np_array = self.cam.capture_array()
        if debug:
            print(np_array.shape)
            cv2.imwrite('new_image.jpg', np_array)

        # crop the image
        if full:
            cropped_image = np_array[720:1830, 1050:2170] # entire puzzle
        else:
            cropped_image = np_array[720:1230, 1050:2170] # "left" half of puzzle

        if debug:
            print(cropped_image.shape)
            cv2.imwrite('cropped_image.jpg', cropped_image)
        
        return cropped_image
    
    def close(self):
        """
        Close the device.
        """
        self.cam.close()
        
    
def main():
    """
    Can be used to tune the cropping parameters.
    """
    camera = SCamera()
    
#     print(camera.camera_controls)
    
    response = ""
    while response == "":
        camera.take_photo(True, True)
        response = input('To continue, hit Enter; to stop, type anything, hit Enter ')
    
    camera.close()

if __name__ == '__main__':
    # print('thru main')
    main()
