import os
import subprocess

from storage.enums import CrcType


def get_json_crc(file_path, crc_type):
    return {'type': crc_type, 'crc': get_file_crc(file_path, crc_type)}


def get_file_crc(file_path, crc_type):
    """ Calculate file CRC
    :param file_path: File, we need to calculate
    :param crc_type: Type of CRC
    :return: Calculated CRC
    """
    if not os.path.exists(file_path):
        raise RuntimeError('No such file ' + file_path)

    if crc_type in CrcType.values:
        return subprocess.run([crc_type, file_path], stdout=subprocess.PIPE).stdout.decode('utf-8').split(' ')[0]

    raise RuntimeError('Bad CRC name ' + crc_type)


def verify_file(file_path, crc, crc_type):
    """ Verify file CRC
    :param file_path: File, we need validate with full path
    :param crc: Saved CRC
    :param crc_type: Type of CRC
    :return:True if CRC is valid
    """
    return crc == get_file_crc(file_path, crc_type)


def verify_file_from_json(file_path, obj):
    return verify_file(file_path, obj['crc'], obj['type'])
