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

import struct
import BaseProc
import os
import logging
import logger
from SG.DataStruct import *

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')
            basename = os.path.basename(inFn)
            if '.t' in basename:
                logp.debug('proce %s add guid the chl no', basename)
                stream = BaseProc.stream2struct(data[0 : sizeof(ver7TStruct)], ver7TStruct)
                stream.dataver = self.new
                stream.GUID[0] = int(os.path.splitext(basename)[0])
                newdata = BaseProc.struct2stream(stream)
                fd.write(newdata)
                fd.write(data[sizeof(ver56TStruct) : ])
            else:
                newVer = struct.pack("<I", self.new)
                fd.write(newVer)
                fd.write(data[4:])
            fd.close()
            return 0
        else:
            logp.error ('old ver in file not equal to' + self.old)
            return 1
