"""
posprinter module - printing with small serial POS printer 

This is done and tested only on STAR Micronics serial printers

Needs: pyserial
"""

import time
import serial
from sys import stdout

class CommandsSerialStar:
    """
        generates commands for serial STAR MICRONICS POS printers
    """
    ESC = "\x1b"
    LF = "\x0a"
    CR = "\x0d"

    def init(self): return self.ESC + "@"
    def feed(self): return self.LF
    def feedlines(self, n): return self.ESC + "a" + chr(1)

class SerialPrinter:

    def __init__(self, port=0, width=42):
        self.cmds = CommandsSerialStar()
        self.width = width
        self.ser = serial.Serial(port)

    def init(self):
        self.ser.write(self.cmds.init())

    def close(self):
        self.ser.close()

    def getPortName(self):
        return self.ser.portstr

    def write(self, string, offset=0, align='left'):
        time.sleep(0.1)
        string = ' '*offset + string
        if align == 'right':
            string = ' '*(self.width - len(string)) + string
        if align == 'center':
            string = ' '*((self.width - len(string))/2) + string
        self.ser.write(string)
        
    def writeln(self, string, offset=0, align='left'):
        self.write(string, offset, align)
        self.feed()

    def line(self, char="-"):
        self.ser.write(char*self.width)
        self.feed()
        
    def feed(self):
        self.ser.write(self.cmds.feed())

    def writeTable(self, data, tabs, format=None):
        """ data = [['art', 'skupina', 'kosov', cena, vrednost],..]
            tabs = (0, 8, 16, 19, 27, 35)
            format =  ('', 'align=right'...)
        """
        for line in data:
            for i in range(len(tabs)-1):
                width = tabs[i+1] - tabs[i] #get width of cell
                text = line[i][0:width]     #trim text to that width
                if format != None:
                    if format[i].find('align=right') >= 0:
                        text = ' '*(width - len(text)) + text
                if len(text) < width:       #if cell has space on right
                    text = text + ' '*(width - len(text)) #write spaces on the right
                self.write(text)            
            self.feed()

			
class ConsolePrinter(SerialPrinter):
    """
        For debuging and testing without real printer mainly
    """

    def __init__(self, consoleStream=None, width=42):
        self.cmds = CommandsSerialStar()
        self.width = width
        if consoleStream:
            self.ser = consoleStream
        else:
            self.ser = stdout

    def init(self):
        pass

    def close(self):
        pass

    def getPortName(self):
        return 'Console Printer, so no port'
		

if __name__ == '__main__':
    pass
