#!/usr/bin/env python

import os, sys
import string
import tempfile

from PyPlucker import PluckerDocs

binary_flag = ""
if sys.platform == 'os2':
    binary_flag = 'b'



class NetPBMImageParser:
    "Convert an image to the PalmBitmap. Uses netpbm."    

    def __init__(self, url, type, data, verbose=0, bpp=1):
        self._type = type
        self._url = url
        self.scale = 0
        self.width = 1
        self.height = 1
        self._verbose = verbose
        self._bpp = bpp
        self._doc = PluckerDocs.PluckerImageDocument(str(url))

	indata = tempfile.mktemp()

	f = open(indata, "w"+binary_flag)
	f.write(data)
	f.close()

        try:
            self._doc.set_data(self.convert_to_Tbmp(indata))        
        except:
            try: os.unlink(indata)
            except: pass
            raise RuntimeError, "Error while converting image."
        try: os.unlink(indata)
        except: pass


    def get_plucker_doc(self):
        return self._doc


    def convert_to_Tbmp(self, indata):
        if self._bpp == 1:
            ncolors = "2"
            ppmtoTbmp = "ppmtoTbmp"
        elif self._bpp == 2:
            ncolors = "4"
            ppmtoTbmp = "ppmtoTbmp -2bit"
        else:
            ncolors = "16"
            ppmtoTbmp = "ppmtoTbmp -4bit"
        if self._verbose <= 1:
            ppmtoTbmp = ppmtoTbmp + " -quiet "
       
        if self._bpp > 1 :
           command = "convert -geometry \"150x250>\" -colors " + ncolors + " -dither " + indata + " ppm:- |" + ppmtoTbmp
	else:  
           command = "convert -geometry \"150x250>\" -monochrome " + indata + " ppm:- |" + ppmtoTbmp


        if self._verbose > 1:
            print "Running: ", command
        pipe = os.popen(command, "r"+binary_flag)
        data = pipe.read()
        pipe.close()
        if len (data) == 0:
           # Oops, nothing fetched?!?
            raise RuntimeError, "No data from parsing image! (%s)" % self._url
        return data
