# This file is part of rmarc. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution and at
# https://opensource.org/licenses/BSD-2-Clause. pymarc may be copied, modified,
# propagated, or distributed according to the terms contained in the LICENSE
# file.

import unittest

import rmarc


class OrderedFieldsTest(unittest.TestCase):
    def test_add_ordered_fields(self):
        record = rmarc.Record()
        for tag in ("999", "888", "111", "abc", "666", "988", "998"):
            field = rmarc.Field(
                tag,
                rmarc.Indicators("0", "0"),
                [rmarc.Subfield(code="a", value="foo")],
            )
            record.add_ordered_field(field)

        # ensure all numeric fields are in strict order
        ordered = True
        last_tag = 0
        for field in record:
            if not field.tag.isdigit():
                continue
            curr_tag = int(field.tag)
            if last_tag > curr_tag:
                ordered = False
            last_tag = curr_tag

        self.assertTrue(ordered, "Fields are not strictly ordered numerically")

    def test_add_grouped_fields(self):
        record = rmarc.Record()
        for tag in ("999", "888", "111", "abc", "666", "988", "998"):
            field = rmarc.Field(
                tag,
                rmarc.Indicators("0", "0"),
                [rmarc.Subfield(code="a", value="foo")],
            )
            record.add_grouped_field(field)

        # ensure all numeric fields are in grouped order
        grouped = []
        for field in record:
            if not field.tag.isdigit():
                continue
            grouped.append(field.tag)

        exp = ["111", "666", "888", "999", "988", "998"]

        self.assertEqual(grouped, exp, "Fields are not grouped numerically")


if __name__ == "__main__":
    unittest.main()
