#
# This file is part of GNU Enterprise.
#
# GNU Enterprise is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2, or (at your option) any later version.
#
# GNU Enterprise is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with program; see the file COPYING. If not,
# write to the Free Software Foundation, Inc., 59 Temple Place
# - Suite 330, Boston, MA 02111-1307, USA.
#
# Copyright 2004-2007 Free Software Foundation
#
# FILE:
# barcodes/code39.py
#
# DESCRIPTION:
"""
Implements the USPS PostNet barcode spec
"""
#

from Base import Barcode, InvalidBarcode

class PostNet(Barcode):
  """
  PostNet
  """
  validLengths = [5,9,11]
  chars = '0123456789'
  mapping = {
    # 1 = tall bar, 2=short bar, 0=space
    '0': '1010202020',
    '1': '2020201010',
    '2': '2020102010',
    '3': '2020101020',
    '4': '2010202010',
    '5': '2010201020',
    '6': '2010102020',
    '7': '1020202010',
    '8': '1020201020',
    '9': '1020102020'
  }

  start = '10'
  stop  = '1'

  lineWidth = 1.44 # points
  lineHeight = 8.5 # (.125")
  spaceWidth = 1.9 #1.66

  encodingMap = {
    # Stroke?, X Multiplier, Y Multiplier
    '0': (False, 1, 1),   # Spaces
    '1': (True, 1, 1),    # Tall bars
    '2': (True, 1, .45)   # Short bars
  }



  defaultIncludeText = False

  # Calculate a Mod-10 check digit
  def checkdigit(self, value):
    v = 0
    for ch in value:
      try:
        v += int(ch)
      except ValueError:
        raise InvalidBarcode
    cd = abs(10-divmod(v,10)[1])
    if cd == 10:
      cd = 0
    return self.chars[cd]


if __name__ == '__main__':

  postnet = PostNet()

  def test(value, format, file):
    f = open(file,'wb')
    postnet.generate(value,f, format)
    f.close()

#   test('381072456','png','test1.png')
#   test('381172459','tiff','test1.tif')
  test('383759907','eps','postnet-1.eps')
  test('12345','eps','postnet-2.eps')
  test('12345678901','eps','postnet-3.eps')
