from datetime import datetime

from jinja2 import Template


def _safe_cdata(value):
    text = "" if value is None else str(value)
    return text.replace("]]>", "]]]]><![CDATA[>")


def render_xml_gruntguru(offer_data_dict, num_photos, option):
    xml_template_insert = """<?xml version="1.0" encoding="UTF-8"?>
<offers export="incremental">
  <offer>
    <id>{{ offer_data.id }}</id>
    <companyId>{{ offer_data.companyId }}</companyId>
    <companyName>{{ offer_data.companyName }}</companyName>
    <mainTypeId dictionary="types">{{ offer_data.mainTypeId }}</mainTypeId>
    <locationLatitude></locationLatitude>
    <locationLongitude></locationLongitude>
    <locationPostal></locationPostal>
    <offerExport>1</offerExport>
    <market dictionary="market">{{ offer_data.market }}</market>
    <transaction dictionary="transaction">{{ offer_data.transaction }}</transaction>
    <number>{{ offer_data.number }}</number>
    <numberExport>{{ offer_data.numberExport }}</numberExport>
    <price>{{ offer_data.price }}</price>
    <priceCurrency dictionary="currency">{{ offer_data.priceCurrency }}</priceCurrency>
    <pricePermeter>{{ offer_data.pricePermeter }}</pricePermeter>
    <areaTotal></areaTotal>
    <areaUsable></areaUsable>
    <areaPlot>{{ offer_data.areaPlot }}</areaPlot>
    <addDate>{{ export_datetime }}</addDate>
    <activateDate>{{ export_datetime }}</activateDate>
    <updateDate>{{ export_datetime }}</updateDate>
    <exportDate>{{ export_datetime }}</exportDate>
    <status dictionary="status">{{ offer_data.status }}</status>
    <portalTitle>{{ offer_data.portalTitle }}</portalTitle>
    <typeName>{{ offer_data.typeName }}</typeName>
    <agreementType dictionary="agreement">{{ offer_data.agreementType }}</agreementType>
    <contactId>{{ offer_data.contactId }}</contactId>
    <contactEmail>{{ offer_data.contactEmail }}</contactEmail>
    <contactFirstname>{{ offer_data.contactFirstname }}</contactFirstname>
    <contactLastname>{{ offer_data.contactLastname }}</contactLastname>
    <contactPhone>{{ offer_data.contactPhone }}</contactPhone>
    <locationCityName>{{ offer_data.locationCityName }}</locationCityName>
    <locationStreetName>{{ offer_data.locationStreetName }}</locationStreetName>
    <locationStreetType>{{ offer_data.locationStreetType }}</locationStreetType>
    <locationPrecinctName>{{ offer_data.locationPrecinctName }}</locationPrecinctName>
    <locationCommuneName>{{ offer_data.locationCommuneName }}</locationCommuneName>
    <locationDistrictName>{{ offer_data.locationDistrictName }}</locationDistrictName>
    <locationProvinceName>{{ offer_data.locationProvinceName }}</locationProvinceName>
    <locationPlaceName>{{ offer_data.locationPlaceName }}</locationPlaceName>
    <locationCountryName>{{ offer_data.locationCountryName }}</locationCountryName>
    <description><![CDATA[{{ offer_data.description_cdata }}]]></description>
    <descriptionWebsite><![CDATA[{{ offer_data.description_website_cdata }}]]></descriptionWebsite>
    <groundPlotwidth>{{ offer_data.groundPlotwidth }}</groundPlotwidth>
    <groundPlotheight>{{ offer_data.groundPlotheight }}</groundPlotheight>
    <groundType dictionary="types">{{ offer_data.groundType }}</groundType>
    <groundFencing dictionary="fence">{{ offer_data.groundFencing }}</groundFencing>
    <groundRoad dictionary="road">{{ offer_data.groundRoad }}</groundRoad>
    <groundOwnership dictionary="ownershipGround">{{ offer_data.groundOwnership }}</groundOwnership>
    <mediaGas dictionary="binary">{{ offer_data.mediaGas }}</mediaGas>
    <mediaCurrent dictionary="binary">{{ offer_data.mediaCurrent }}</mediaCurrent>
    <mediaSewerage dictionary="binary">{{ offer_data.mediaSewerage }}</mediaSewerage>
    <action>{{ offer_data.action }}</action>
    <pictures>{% for i in range(num_photos) %}
      <picture type="119">image_{{ offer_data.id }}_url_{{ i }}.jpg</picture>{% endfor %}
    </pictures>
  </offer>
</offers>"""

    xml_template_delete = """<?xml version="1.0" encoding="UTF-8"?>
<offers export="incremental">
  <offer>
    <id>{{ offer_data.id }}</id>
    <companyId>{{ offer_data.companyId }}</companyId>
    <action>delete</action>
  </offer>
</offers>"""

    render_payload = dict(offer_data_dict)
    render_payload["description_cdata"] = _safe_cdata(offer_data_dict.get("description", ""))
    render_payload["description_website_cdata"] = _safe_cdata(offer_data_dict.get("descriptionWebsite", ""))

    template = Template(xml_template_delete if option == "delete" else xml_template_insert)
    return template.render(
        offer_data=render_payload,
        num_photos=num_photos,
        export_datetime=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    )
