import logging
import hashlib


def verify(checksums):
    """
    Verify if all given files are present and their SHA256 
    checksum is correct. Any files not explicitly listed are deleted.
    
    checksums is a dict of file => checksum, with file a file relative to dir.
    
    Returns a boolean indicating that all checksums are correct, and all files 
    are present.
    
    Any warnings and errors are printer to logger.
    Errors or exceptions result in a return value of False.
    """
    logger = logging.getLogger("nbt.tests.downloadsample")
    success = True
    for path in checksums.keys():
        try:
            check = checksums[path]
            if check == None: continue  # Skip folders
            localfile = open(path, 'rb')
            h = hashlib.sha256()
            chunksize = 524288 # 0.5 MiB
            while True:
                data = localfile.read(chunksize)
                if not data: break
                h.update(data)
            localfile.close()
            calc = h.hexdigest()
            if calc != check:
                logger.error("Checksum failed %s: %s found, %s expected" % (path, calc, check))
                success = False
        except IOError as e:
            if e.errno == 2:
                logger.error('Checksum verificiation failed: file %s not found' % e.filename)
            else:
                logger.error('Checksum verificiation of %s failed: errno %d: %s' % \
                        (e.filename, e.errno, e.strerror))
            return False
    logger.info("Checksum of %d files verified" % len(checksums))
    return success