#!/usr/bin/python3

import argparse
from lxml.builder import ElementMaker
import lxml.etree as etree

import filing
from profile import Profile
from surks import Surks
from xpaths import Xpaths
from nitpo import Nitpo


desc = 'add a surk like fecha'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-v', action='store_true', help='do verbose')
parser.add_argument('repcode', type=str, help='repcode')
parser.add_argument('emad', type=str, help='emad')
args = parser.parse_args()
repcode = args.repcode
emad = args.emad

profile = Profile()
nsmap = "{%s}" % profile.const['ns']
em = ElementMaker(nsmap={None: profile.const['ns']})
web_ele = em(nsmap + 'web')
web_ele.attrib['emad'] = emad
web_ele.attrib['repcode'] = repcode
string = etree.tostring(web_ele, pretty_print=True).decode()
surks = Surks()
xpaths = Xpaths()

profile = Profile()
profile_doc = profile.load(emad)

bounced = profile.is_bounced(profile_doc)
if bounced is not None:
    web_ele.attrib['bounced'] = bounced
    quit()
## web_ele contains the profile_doc
web_ele = surks.fecha_add(profile_doc, repcode, emad, web_ele)
print(etree.tostring(web_ele, pretty_print=True).decode())
if 'changed' not in web_ele.attrib:
    # # no change
    quit()
profile_ele = xpaths.none_or_one(web_ele, '/n:web/n:profile')
if profile_ele is None:
    # # nothing to write, should not be the case
    quit()
print(etree.tostring(web_ele, pretty_print=True).decode())
profile.doc = etree.ElementTree(profile_ele)
print('write')
profile.write(profile_doc)
filing.install_xml(web_ele, '/tmp/web.xml')