'''
Created on Feb 02, 2013

@author: Jose Sal y Rosas
@contact: arturo.jasyrc@gmail.com
'''

import zlib
import hashlib


class Verificator(object):

    def __init__(self):
        pass

    def set_parameters(self, path='', algorithm='crc32', blocksize=8192):
        self.path = path
        self.algorithm = algorithm
        self.blocksize = blocksize

    def set_algorithm(self, algorithm):
        self.algorithm = algorithm

    def set_file(self, path):
        self.path = path

    def set_block_size(self, blocksize):
        self.blocksize = blocksize

    def get_algorithm(self):
        return self.algorithm

    def get_file(self):
        return self.path

    def get_block_size(self):
        return self.blocksize

    def generatechecksum(self, path='', blocksize=8192):
        resultado = 0
        if path == '':
            path = self.path

        if blocksize == 8192:
            blocksize = self.blocksize

        if 'crc32' in self.algorithm:
            resultado = self.executecrc(path, blocksize)

        elif 'md5' in self.algorithm:
            resultado = self.executemd5(path, blocksize)

        return resultado

    def executecrc(self, path, blocksize):
        crctemp = 0

        with open(path, 'rb') as f:
            while True:
                data = f.read(blocksize)
                if not data:
                    break
                crctemp = zlib.crc32(data, crctemp)
            return crctemp

    def executemd5(self, path, blocksize):
        with open(path, 'rb') as f:
            m = hashlib.md5()
            while True:
                data = f.read(blocksize)
                if not data:
                    break
                m.update(data)
            return m.hexdigest()

    def verify(self, path, checksum):
        if checksum == self.generatechecksum(path):
            return 'suceed'
        else:
            return 'failed'


if __name__ == "__main__":
    path = '/home/developer/Documents/database/datos/iniciales/EW_Drift+Faraday/EW_Drift/d2012219/D2012213003.r'
    obj = Verificator()
    obj.set_parameters(path, 'md5')
    checksum = obj.generatechecksum()
    print checksum
    print obj.verify(path, checksum)