"""IMM1294 current-spouse writes must preserve previous-spouse containers."""
import json
from pathlib import Path
import unittest
from uuid import uuid4
import xml.etree.ElementTree as ET

import pikepdf
from prefill_imm_xfa_pdf import fill, find_by_path

BASE = Path(__file__).resolve().parents[2]


class Imm1294SpousePathsTest(unittest.TestCase):
    def test_current_and_previous_given_names_are_independent_in_both_orders(self):
        work = BASE / 'storage/app/imm/tmp' / ('1294-spouse-' + uuid4().hex)
        work.mkdir(parents=True)
        for language in ('en', 'fr'):
            for previous in ('PREVIOUS NAME', ''):
                for reverse in (False, True):
                    fields = [('MaritalStatus.SectionA.GivenName', 'CURRENT NAME'),
                              ('MaritalStatus.SectionA.GivenName.PMGivenName', previous)]
                    if reverse:
                        fields.reverse()
                    source = work / (uuid4().hex + '.json')
                    source.write_text(json.dumps({'form': 'IMM1294', 'language': language, 'fields': dict(fields)}))
                    output = source.with_suffix('.pdf')
                    blank = BASE / 'storage/app/imm' / ('imm1294e.pdf' if language == 'en' else 'imm1294f.pdf')
                    fill(source, output, blank)
                    with pikepdf.open(output) as pdf:
                        xfa = pdf.Root.AcroForm.XFA
                        raw = next(xfa[i+1].read_bytes() for i in range(0, len(xfa), 2) if str(xfa[i]) == 'datasets')
                    root = ET.fromstring(raw)
                    self.assertEqual(find_by_path(root, 'form1.Page1.MaritalStatus.SectionA.GivenName')[0].text, 'CURRENT NAME')
                    nodes = find_by_path(root, 'form1.Page2.MaritalStatus.SectionA.GivenName.PMGivenName')
                    self.assertEqual(len(nodes), 1)
                    self.assertEqual(nodes[0].text or '', previous)
