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

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

logp = logger.FinalLogger.getLogger()

class ver7To8(BaseProc.BaseProc):
    def __init__(self):
        BaseProc.BaseProc.__init__(self, 7, 8)

    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(ver7TMsgSaveEngine)], ver7TMsgSaveEngine)
            stream.prev7data.dataVer = self.new
            
            #首次转换时,写入相关内容到文件
            if (inDst == self.old):
                dataSer = dataSerial.DataSerial.getDataSerial(inDstTopDir)
                dataSer.debug("%d-%d-%d-%d-%d", stream.prev7data.channelNoInfoRow,\
                              stream.prev7data.channelNoInfoCol, stream.prev7data.channelNoInfoIndex,\
                              stream.prev7data.testId, stream.prev7data.dfDataIndex - 1)
                
            if inTID:#测试ID不为0时,更新
                stream.prev7data.testId = inTID
                
            newdata = BaseProc.struct2stream(stream)
            fd.write(newdata[0 : sizeof(ver8ChangeStart) - 24 * 4 - 3])
            npose = sizeof(ver8ChangeStart) - 24 * 4 - 3
            #写入24个float内容
            cnt = 0
            while cnt < 24:
                fd.write(struct.pack("<I", 0))
                cnt += 1
            #写入-3个的内容
            fd.write(data[npose : npose + 3])
            npose += 3
            #跳过("reserveStopCount", c_uint), ("appointStepCount", c_uint),
            npose += 8
            #写入TResePauseInfo
            inull = TResePauseInfo(0)
            fd.write(inull)
            #写入其它内容
            fd.write(data[npose : npose + sizeof(ver8Tail) - 1])
            #写入新添加的内容
            ida = b"\0"
            ibyte = struct.pack("c", ida)
            fd.write(ibyte)
            #写入结构体之外的内容
            npose += (sizeof(ver8Tail) - 1)
            fd.write(data[npose : len(data) - 4])
            fd.close()

            #打开读取,计算CRC并写入
            fd = open(inFn, 'rb')
            data = fd.read()
            fd.close()

            crc32 = binascii.crc32(data[4 : len(data)])
            fd = open(inFn, 'wb')
            fd.write(data[0:])
            fd.write(struct.pack("<I", crc32))
            fd.close()
            return 0            
        else:
            logp.error ('old ver in file not equal to' + self.old)
            return 1
