'''
Created on 24 Jan 2017
@author: muth    
'''
import os
import RPi.GPIO as GPIO
import threading
import time
from Adafruit_Thermal import *
from time import sleep
from PIL import Image
from PIL import ImageOps
from PIL import ImageEnhance
from PIL import ImageDraw
from PIL import ImageFont
from smemlcd import SMemLCD
from picamera import PiCamera
from io import BytesIO
from subprocess import check_output

# Constants
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 240
SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)
PRINTER_WIDTH = 640
PRINTER_HEIGHT = 384
PRINTER_SIZE = (PRINTER_WIDTH, PRINTER_HEIGHT)
FILE_WIDTH = PRINTER_WIDTH*2
FILE_HEIGHT = PRINTER_HEIGHT*2
FILE_SIZE = (FILE_WIDTH, FILE_HEIGHT)

SHOT_PIN = 16
PRINT_PIN = 15
NEXT_PIN = 13
PREV_PIN = 11
HALT_PIN = 31
FRAME_MODE = 1
SCAN_MODE = 2
SCAN_MODE_FIX = 3

class SlitScan(object):
    def __init__(self):
        self.image_scan = Image.new('L', PRINTER_SIZE, 0)
        self.x = 0
        self.mode = FRAME_MODE
        self.scanDone = False
        self.lastTime = time.time()
        self.ditherMode = Image.ORDERED
        
    def write(self, s):
        global lcd
        image = Image.frombuffer('L', PRINTER_SIZE, s, "raw", 'L', 0, 1)
        
        if self.mode == FRAME_MODE:
            image.thumbnail(SCREEN_SIZE, Image.NEAREST)
            image = ImageOps.invert(image)
            image = image.convert('1', dither=self.ditherMode)
            
        if self.mode == SCAN_MODE:
            image = image.crop((self.x, 0, self.x+1, PRINTER_HEIGHT))
            self.image_scan.paste(image,(self.x, 0))
            
            if self.x < PRINTER_WIDTH-1:
                self.x += 1
            else:
                self.scanDone = True
                
            image = ImageOps.invert(self.image_scan)