#!/usr/bin/env python
# -*- coding: cp936 -*-

import struct
import BaseProc
import os
from ES.DataStruct import *
import logging
from ctypes import *
import binascii
import logger
import dataSerial

logp = logger.FinalLogger.getLogger()

class ver5To6(BaseProc.BaseProc):
    def __init__(self):
        BaseProc.BaseProc.__init__(self, 5, 6)

    def process(self, inFn, inTID, inDst, inDstTopDir):
        logp.debug ('%d to %d with test id %d', self.old, self.new, inTID)
        fd = open(inFn, 'rb')
        data = fd.read()
        fd.close()
        if (self.old == struct.unpack("<I",data[0:4])[0]):
            os.rename(inFn, inFn + '.pre' + str(self.old))
            fd = open(inFn, 'wb')

            stream = BaseProc.stream2struct(data[0 : sizeof(ver5TMsgSaveEngine)], ver5TMsgSaveEngine)
            stream.dataVer = self.new
            
            #首次转换时,写入相关内容到文件
            if (inDst == self.old):
                dataSer = dataSerial.DataSerial.getDataSerial(inDstTopDir)
                dataSer.debug("%d-%d-%d-%d-%d", stream.channelNoInfoRow, stream.channelNoInfoCol, stream.channelNoInfoIndex, stream.testId, stream.dfDataIndex - 1)
                
            if inTID:#测试ID不为0时,更新
                stream.testId = inTID
            
            newdata = BaseProc.struct2stream(stream)
            fd.write(newdata)
            npose = sizeof(ver5TMsgSaveEngine)
            fd.write(data[npose:len(data) - 4])
            crc32 = binascii.crc32(newdata[4:])
            crc32 = binascii.crc32(data[npose : len(data) - 4], crc32)
            fd.write(struct.pack("<I", crc32))
            fd.close()
            return 0
        else:
            logp.error ('old ver in file not equal to' + self.old)
            return 1
