import zlib
import os
import hash_util as HashUtil

#TEST
home = "./"

def get_crc(file_path):
    crc = 0
    print "a"
    try:
        with open(file_path, "rb") as f:
            buf = f.read()
            print buf
            crc =  HashUtil.hash(buf)
            print crc
    except Exception, e:
        print e
        return 0
    return crc & 0xffffffff

def delete(file_name):
    pass


def save(file_name, pos, data):
    tmp_file = os.path.join(home, file_name + ".tmp")

    if pos == 0:
        if os.path.exists(tmp_file):
            try:
                os.remove(tmp_file)
            except Exception:
                print "error1"
    else:
        if not os.path.exists(tmp_file) or os.path.getsize(tmp_file) < pos:
            return 
    mode = "w+b" if pos == 0 else "r+b"
    try:
        with open(tmp_file, mode) as raf:
            raf.seek(pos)
            raf.write(data)
        print "ok"
    except Exception:
        print "error2"

def done(file_name, size, crc32):
    tmp_file = os.path.join(home, file_name + ".tmp")
    if not os.path.exists(tmp_file) or os.path.getsize(tmp_file) != size:
        return 

    fcrc = get_crc(tmp_file)
    if fcrc == 0 or fcrc != crc32:
        return 

    final_file = os.path.join(home, file_name)
    try:
        os.rename(tmp_file, final_file)
    except Exception:
        pass



if __name__ == "__main__":
    test_file = "whatap_infra"
    test_data = b"TEST, DATA"
    save(test_file, 0, test_data)

    tmp_path = os.path.join(home, test_file + ".tmp")
    if os.path.exists(tmp_path):
        file_size = os.path.getsize(tmp_path)
        file_crc = get_crc(tmp_path)
        print("Saved tmp file size:", file_size)
        print("Saved tmp file crc32:", file_crc)
        done(test_file, file_size, file_crc)
        final_path = os.path.join(home, test_file)
        if os.path.exists(final_path):
            print("Final file exists:", final_path)
                                                                                                
