# -*- coding:utf-8 -*-
"""
/***************************************************************************
 xfdf_receipt.py

 XfdfReceipt class prepare XFDF file in memory

 For XFDF specifications see :
 https://www.iso.org/obp/ui/fr/#iso:std:iso:19444:-1:ed-2:v1:en
 and Adobe implementation :
 https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/formsys.pdf

        begin                : 2020-10-15
        git sha              : $Format:%H$
        copyright            : (C) 2020 by Jean-Marie Arsac
        email                : jmarsac@azimut.fr
        
  Although yattag (https://www.yattag.org/) is a nice and powerful python
  library to create XML/HTML files, we use lxml since it is supplied with 
  QGIS (http://lxml.de/tutorial.html#the-e-factory).
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
 """
from lxml import builder, etree


class XfdfReceipt:
    def __init__(self):
        """Constructor"""
        self.__xfdf_version = "1.0"

    def open(self, filename):
        self.__filename = filename
        self.__root = etree.Element("xfdf", xmlns="http://ns.adobe.com/xfdf/")
        f = etree.Element("f", href=self.__filename + ".pdf")
        self.__root.append(f)
        self.__fields = etree.Element("fields")

    def close(self):
        self.__root.append(self.__fields)

    def display(self):
        print(etree.tostring(self.__root, pretty_print=True))

    def save_to_file(self, target_path):
        self.__receipt = etree.ElementTree(self.__root)
        self.__receipt.write(target_path, xml_declaration=True, encoding="UTF-8")

    def add_checkbox_value(self, true_false, tag_name):
        on_off = "Oui" if true_false == True else "Off"
        field = etree.Element("field", name=tag_name)
        value = etree.Element("value")
        value.text = on_off
        field.append(value)
        self.__fields.append(field)

    def add_text_value(self, value, tag_name):
        if value and tag_name:
            field = etree.Element("field", name=tag_name)
            field_value = etree.Element("value")
            field_value.text = value
            field.append(field_value)
            self.__fields.append(field)

    def get_receipt(self):
        return etree.ElementTree(self.__root)
