# Copyright (c) 2013-2015 Unidata.
# Distributed under the terms of the MIT License.
# SPDX-License-Identifier: MIT

from io import BytesIO
from siphon.testing import get_recorder
from siphon.cdmr.ncstream import read_ncstream_messages, read_var_int
from siphon.cdmr.ncStream_pb2 import Header

HEAD_LOCATION_DEFAULT = ''
HEAD_TITLE_DEFAULT = ''
HEAD_ID_DEFAULT = ''
HEAD_VERSION_DEFAULT = 0

recorder = get_recorder(__file__)


@recorder.use_cassette('latest_rap_catalog')
def get_test_latest_url(query=None):
    from siphon.catalog import TDSCatalog
    cat = TDSCatalog('http://thredds-test.unidata.ucar.edu/thredds/catalog/'
                     'grib/NCEP/RAP/CONUS_13km/latest.xml')
    url = list(cat.datasets.values())[0].access_urls['CdmRemote']
    if query:
        url += '?' + query
    return url


@recorder.use_cassette('latest_rap_ncstream_header')
def get_header_remote():
    from siphon.http_util import urlopen
    return urlopen(get_test_latest_url('req=header'))


def test_var_int():
    for src, truth in [(b'\xb6\xe0\x02', 45110), (b'\x17\n\x0b', 23)]:
        yield check_var_int, src, truth


def check_var_int(src, result):
    read_var_int(BytesIO(src)) == result


def test_header_message_def():
    f = get_header_remote()
    messages = read_ncstream_messages(f)
    assert len(messages) == 1
    assert isinstance(messages[0], Header)
    head = messages[0]
    # test that the header message definition has not changed!
    test = head.location == HEAD_LOCATION_DEFAULT
    assert [test, not test][head.HasField("location")]
    test = head.title == HEAD_TITLE_DEFAULT
    assert [test, not test][head.HasField("title")]
    test = head.title == HEAD_ID_DEFAULT
    assert [test, not test][head.HasField("id")]
    test = head.title == HEAD_VERSION_DEFAULT
    assert [test, not test][head.HasField("version")]


def test_remote_header():
    f = get_header_remote()
    messages = read_ncstream_messages(f)
    assert len(messages) == 1
    assert isinstance(messages[0], Header)

    head = messages[0]
    # make sure fields in the message are set to non-default values
    #  when HasField returns True
    for field in head.ListFields():
        fname = field[0].name
        if not fname == "root":
            test = eval("head.{} == HEAD_{}_DEFAULT".format(fname, fname.upper()))
            assert eval("[{}, not {}][head.HasField('{}')]".format(test, test, fname))


def test_local_data():
    f = BytesIO(b'\xab\xec\xce\xba\x17\n\x0breftime_ISO\x10\x07\x1a\x04\n'
                b'\x02\x10\x01(\x02\x01\x142014-10-28T21:00:00Z')
    messages = read_ncstream_messages(f)
    assert len(messages) == 1
    assert messages[0][0] == '2014-10-28T21:00:00Z'

@@ -292,106 +292,8 @@
 er%0A%0A
-HEAD_LOCATION_DEFAULT = ''%0AHEAD_TITLE_DEFAULT = ''%0AHEAD_ID_DEFAULT = ''%0AHEAD_VERSION_DEFAULT = 0%0A%0A
 reco
@@ -1131,650 +1131,40 @@
     
-f = get_header_remote()%0A    messages = read_ncstream_messages(f)%0A    assert len(messages) == 1%0A    assert isinstance(messages%5B0%5D, Header)%0A    head = messages%5B0%5D%0A    # test that the header message definition has not changed!%0A    test = head.location == HEAD_LOCATION_DEFAULT%0A    assert %5Btest, not test%5D%5Bhead.HasField(%22location%22)%5D%0A    test = head.title == HEAD_TITLE_DEFAULT%0A    assert %5Btest, not test%5D%5Bhead.HasField(%22title%22)%5D%0A    test = head.title == HEAD_ID_DEFAULT%0A    assert %5Btest, not test%5D%5Bhead.HasField(%22id%22)%5D%0A    test = head.title == HEAD_VERSION_DEFAULT%0A    assert %5Btest, not test%5D%5Bhead.HasField(%22version%22)%5D%0A%0A%0Adef test_remote_header():
+'Test parsing of Header message'
 %0A   
@@ -1302,17 +1302,16 @@
 Header)%0A
-%0A
     head
@@ -1333,373 +1333,263 @@
     
-# make sure fields in the message are set to non-default values%0A    #  when HasField returns True%0A    for field in head.ListFields():%0A        fname = field%5B0%5D.name%0A        if not fname == %22root%22:%0A            test = eval(%22head.%7B%7D == HEAD_%7B%7D_DEFAULT%22.format(fname, fname.upper()))%0A            assert eval(%22%5B%7B%7D, not %7B%7D%5D%5Bhead.HasField('%7B%7D')%5D%22.format(test, test, fname))
+assert head.location == ('http://thredds-test.unidata.ucar.edu/thredds/cdmremote/grib/'%0A                             'NCEP/RAP/CONUS_13km/RR_CONUS_13km_20150519_0300.grib2')%0A    assert head.title == ''%0A    assert head.id == ''%0A    assert head.version == 1
 %0A%0A%0Ad

Make header test less of protobuf implementation.