#
# Purpose: Write 2 new JPG image files => PicSeal JPG Files
#
# Data: public key, private key, image hash, image signature
# Has: JPG fingerprint
#
# Big-endian
# Pub: [picseal:7|type:1|sig:512|pubkey:550]
# Pvt: [picseal:7|type:1|sig:512|pvtkey:2347]
#
import struct
import logging
from Crypto.PublicKey import RSA

class JpgPicSeal:

  app15_marker   = b'\xff\xef'
  # ascii code for "picseal"
  picseal_marker = b'\x70\x69\x63\x73\x65\x61\x6C'


  def __init__(self, sig=None):
    self.sig = sig
    self.sig_data = None
    

  #
  # READ
  #

  def isPicSeal(self, buf):
    if (buf == JpgPicSeal.picseal_marker):
      return True
    return False

  #
  def deserialize(self, fhr):
    # read type 0x01 is public key, 0x02 private key
    buf = fhr.read(1)
    pubpvt = struct.unpack('>B', buf)
    self.sig_data = fhr.read(512)
    if (pubpvt == b'\x01'):
      #pub
      buf = fhr.read(550)
      self.sig.importPubKey(buf)
    else:
      #pvt
      buf = fhr.read(2347)
      self.sig.importPvtKey(buf)



  def readPub(self):
    pass

  def readPvt(self):
    pass



  #
  # WRITE
  #

  #
  def serilize(self, fname):
    pass
  #
  # input is the Crypto Sig class
  #
  def writePub(self, fhw):
    self.__writeData(fhw, self.sig.sig_data, self.sig.getPubKeyDER(), b'\x01')

  #
  # input is the Crypto Sig class
  #
  def writePvt(self, fhw):
    self.__writeData(fhw, self.sig.sig_data, self.sig.getPvtKeyDER(), b'\x02')


  #
  def __writeData(self, fhw, sig_data, keyder, pubpvt):
    # must include 2 bytes of length too
    size = 2
    size += len(JpgPicSeal.picseal_marker)
    size += len(sig_data)
    size += len(keyder)

    logging.debug("picseal marker length: {}".format(str(len(JpgPicSeal.picseal_marker))))
    logging.debug("hash size: {}".format(str(len(sig_data))))
    logging.debug("key size: {}".format(str(len(keyder))))

    #
    # write header
    # write app marker
    fhw.write(JpgPicSeal.app15_marker)
    # write the size of picseal record
    fhw.write(size.to_bytes(2, byteorder='big'))

    #
    # write picseal data
    # write picseal marker
    fhw.write(JpgPicSeal.picseal_marker)
    fhw.write(pubpvt)
    # write hash of image
    fhw.write(sig_data)  
    # write the public key data
    fhw.write(keyder)

