import io
import pycurl
from lxml import etree as ET

def fetch_icon(settings_xml):
    root = ET.fromstring(settings_xml.encode())

    icon_url = root.find(".//icon_url").text
    method = root.find(".//method").text
    body = root.find(".//body").text if root.find(".//body") else None

    if icon_url == "DEFAULT":
        return (open("./app/static/blowfish.svg"), "image/svg+xml")

    buffer = io.BytesIO()
    c = pycurl.Curl()
    c.setopt(pycurl.URL, icon_url.encode("latin1"))
    c.setopt(pycurl.CUSTOMREQUEST, method.encode("latin1"))
    c.setopt(pycurl.WRITEDATA, buffer)
    c.setopt(pycurl.TIMEOUT, 5)
    c.setopt(pycurl.SSL_VERIFYPEER, 0)
    c.setopt(pycurl.SSL_VERIFYHOST, 0)
    c.setopt(pycurl.PROTOCOLS, pycurl.PROTO_HTTP | pycurl.PROTO_HTTPS)
    c.setopt(pycurl.REDIR_PROTOCOLS, pycurl.PROTO_HTTP | pycurl.PROTO_HTTPS)

    if body:
        c.setopt(pycurl.POSTFIELDS, body.encode("latin1"))

    c.perform()
    c.close()

    return (buffer.getvalue(), "image/png")
