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

import struct
import BaseProc
import os
import proc0.DataStruct
import logging
import binascii
import logger

logp = logger.FinalLogger.getLogger()

class ver6To7(BaseProc.BaseProc):
    def __init__(self):
        BaseProc.BaseProc.__init__(self, 6, 7)

    def process(self, inFn):
        logp.debug ('%d to %d', self.old, self.new)
        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')
            newVer = struct.pack("<I", self.new)
            fd.write(newVer)
            ''' 写入上一个版本除CRC的数据内容'''
            fd.write(data[4:len(data) - 4])
            fd.write(struct.pack("<I", 0))#'''ddAlarmLightConfig'''
            fd.write(struct.pack("<I", 0x5a5aa5a5))#'''ddAlarmLightConfig'''
            
            fd.write(struct.pack("<I", 24))#'''ddChannelCountConfig'''
            fd.write(struct.pack("<I", 0x5a5aa5a5))#'''ddChannelCountConfig'''
            
            fd.write(struct.pack("<I", 4))#'''ddFloorConfig'''
            fd.write(struct.pack("<I", 0x5a5aa5a5))#'''ddFloorConfig'''

            fd.write(struct.pack("<I", 3))#'''ddTechnologyConfig'''
            fd.write(struct.pack("<I", 0x5a5aa5a5))#'''ddTechnologyConfig'''
            
            fd.write(struct.pack("<I", 12))#'''ddPLCTypeConfig'''
            fd.write(struct.pack("<I", 0x5a5aa5a5))#'''ddPLCTypeConfig'''
            fd.close()

            fd = open(inFn, 'rb')
            data = fd.read()
            fd.close()
            
            crc32 = binascii.crc32(data[4 : len(data) - 4])
            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
