import requests
import re


def check_tfchain_synced(prefab, height_threeshold=10):
    """
    Check if the tfchain daemon is synced with the offical testnet
    @param prefab: prefab of the TFT node
    @param height_threeshold: The max difference between the testnet explorer and the local node to be considered in sync
    """
    testnet_explorer = 'https://explorer.testnet.threefoldtoken.com/explorer'
    res = requests.get(testnet_explorer)
    if res.status_code == 200:
        expected_height = res.json()['height']
        _, out, err = prefab.core.run(cmd='tfchainc', showout=False)
        out = '{}\n{}'.format(out, err)
        match = re.search('^Synced:\s+(?P<synced>\w+)\n*.*\n*Height:\s*(?P<height>\d+)', out)
        if match:
            match_info = match.groupdict()
            if match_info['synced'] == 'Yes' and expected_height - int(match_info['height']) <= height_threeshold:
                return True
    return False