#
# 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 Interleaved 2 of 5 barcode spec
"""
#

from Base import Barcode

class Interleaved2of5(Barcode):
  chars = '0123456789'

  # Interleaved works differently than the others
  mapping = {
    '0': 'NNWWN',
    '1': 'WNNNW',
    '2': 'NWNNW',
    '3': 'WWNNN',
    '4': 'NNWNW',
    '5': 'WNWNN',
    '6': 'NWWNN',
    '7': 'NNNWW',
    '8': 'WNNWN',
    '9': 'NWNWN'
  }

  lineWidth = .6 # points (7.5mil)
  lineHeight = 18 # Actually dependent on the width

  start = 'NnNn'
  stop  = 'WnN'

  encodingMap = {
         # Stroke?, X Multiplier, Y Multiplier
    'n': (False, 1, 1),   # Narrow Spaces
    'w': (False, 2.5, 1),   # Wide Spaces
    'N': (True, 1, 1),    # Narrow bars
    'W': (True, 2.5, 1)   # Wide bars
  }

  calculateLineHeight = Barcode._calculate15

  # Since this is interleaved, we do
  # our own custom buildBinary.
  def _buildBinary(self, value):
    """
    Returns a string of 0s (no line) and 1s (line).
    Note that, depending on the barcode type,
    a single bar could be multiple
    """

    value = str(value)
    if len(value)/2.0 != int(len(value)/2.0):
      raise InvalidBarcode, \
          'Interleaved 2of5 must have an even number of digits'

    rv = self.start

    even = False
    for i in range(len(value)/2):
      try:
        bar = self.mapping[value[i]]
        space = self.mapping[value[i+1]].lower()
      except KeyError:
        raise InvalidBarcode

      for j in xrange(5):
        rv += bar[j]
        rv += space[j]

    return rv + self.stop


if __name__ == '__main__':

  testbar = Interleaved2of5()

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

#   test('0123456789','png','test1.png')
#   test('9876543210','tiff','test1.tif')
  test('0123456789','eps','i2of5-1.eps')
  test('9876543210','eps','i2of5-1.eps')
