#
#
#
import os
import logging
from libs.jpg_bin import JpgBin
from libs.jpg_bin_w import JpgBinWrite
from libs.crypto_sig import Signature
from libs.toolbox import Toolbox


class JpgProc:

  PSPUB = "PSPUB"
  PSPVT = "PSPVT"

  def __init__(self):
    self.fh  = None
    self.fn  = ""
    self.jpg = None
    self.sig = None
    self.is_processed = False

  #
  # process a jpg file, read only
  #
  def process(self, fname):
    self.fh = open(fname, "rb")
    self.fn = fname
    self.jpg = JpgBin()
    retval = self.jpg.processFile(self.fh)
    logging.info("processFile()=={}".format(retval))
    self.is_processed = True
    return self.jpg

  #
  # hash the jpg image data
  #
  def hash(self):
    if (not self.is_processed):
      return 0xdeadbeef

    # hash the jpg image data
    self.sig = Signature()
    img_hash = self.jpg.genHash(self.sig.hh)
    logging.info("img_hash-size=={}, img_hash=={}".format(len(img_hash), img_hash))
    return img_hash

  #
  def writePicSealJpg(self, fname=None):
    if not fname:
      fname = self.fn

    (fname_pub, fname_pvt) = JpgProc.__getFileNames(fname)

    # Write a new JPG PicSeal file w/ Public Key
    self.fh.seek(0)
    fhw = open(fname_pub, "xb")
    jpgw = JpgBinWrite(self.fh, fhw)
    jpgw.writeJpgPicSealPub(self.sig, self.jpg.jpg_fp)

    # Write a new JPG PicSeal file w/ Private Key
    self.fh.seek(0)
    fhw = open(fname_pvt, "xb")
    jpgw = JpgBinWrite(self.fh, fhw)
    jpgw.writeJpgPicSealPvt(self.sig, self.jpg.jpg_fp)


  #
  def __getFileNames(image_fn):
    basename = os.path.basename(image_fn)
    (filename, ext) = Toolbox.parseFilenameIncExt(basename)
    pubFileName = filename + '_' + JpgProc.PSPUB + '_' + Toolbox.getTimestampStr() + ext
    pvtFileName = filename + '_' + JpgProc.PSPVT + '_' + Toolbox.getTimestampStr() + ext
    return (pubFileName, pvtFileName)

