#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
 79版本的程序：4S_0.4.7.19_20140408_093529.bin 通过 BTS7.5.4.173（2013.09.11）（R3）
 的客户端，将数据拿上来后，再经过这些处理为 数据版本为2的版本：4S_1.0.0.6_20140403_151700.rar
以上的版本，后面已做处理。 
'''

import struct
import BaseProc
import os
import binascii
from CycleData.DataStruct import *
import logging
import logger

logp = logger.FinalLogger.getLogger()

class ver1To2(BaseProc.BaseProc):
    def __init__(self):
        BaseProc.BaseProc.__init__(self, 1, 2)

    def process(self, inFn):
        
        logp.debug ('%d to %d', self.old, self.new)
        fd = open(inFn, 'rb')
        data = fd.read()
        fd.close()
        fid = open(os.path.split(inFn)[0]+"/TestIDMgr", 'rb')
        dataID = fid.read()
        fid.close()

        ##del TestIDMgr
        os.remove(os.path.split(inFn)[0]+"/TestIDMgr")
        
        if (self.old == struct.unpack("<I",data[0:4])[0]):
            os.rename(inFn, inFn + '.pre' + str(self.old))
            fd = open(inFn, 'wb')
            newVer = struct.pack("<I", self.new)
            fd.write(newVer)
            ######### 
            streamV1 = BaseProc.stream2struct(data[4 : sizeof(ver1TChTable) + 4], ver1TChTable)
            streamID = BaseProc.stream2struct(dataID[4 : sizeof(ver1TestIDTbl) + 4], ver1TestIDTbl)
            streamV2 = ver2TMapTbl()
            for i in range(256):
                streamV2.mapTable[i].chlMap.rowID = streamV1.channelMapTbl[i].rowID
                streamV2.mapTable[i].chlMap.colID = streamV1.channelMapTbl[i].colID
                streamV2.mapTable[i].chlMap.index = streamV1.channelMapTbl[i].index
                streamV2.mapTable[i].testID = streamID.mTestIDTbl[i].testID
                streamV2.mapTable[i].syncMap.syncNo = 0xffff
                streamV2.mapTable[i].syncMap.syncIndex = 0
                '''logp.debug(i,streamV2.mapTable[i].chlMap.rowID,
                      streamV2.mapTable[i].chlMap.colID,
                      streamV2.mapTable[i].chlMap.index,
                      streamV2.mapTable[i].testID)'''
            streamV2.writeSer = 1

            datalast = BaseProc.struct2stream(streamV2)
            crc32 = binascii.crc32(datalast)
            fd.write(datalast[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
