import xml.etree.ElementTree as ET
import requests
import tempfile


def _load_into_file(url):
    response = requests.get(url)
    response.raise_for_status()

    with tempfile.NamedTemporaryFile(delete=False) as temp_file:
        temp_file.write(response.content)
        return temp_file


def _is_capabilites_response(file):
    with open(file.name, "rb") as f:
        try:
            xml = ET.parse(f).getroot()

            return xml.tag == "{http://www.opengis.net/wms}WMS_Capabilities"
        except ET.ParseError:
            return False


def is_valid(resource, file):
    if _is_capabilites_response(file):
        return True

    # The response is not a capabilites XML files. That is allowed.
    # Let's add the request parameters to the URL and try again.

    url = resource["url"]
    if "request=" not in url.lower():
        if not url.endswith("?"):
            url = url + "?"

        url = url + "service=WMS&request=GetCapabilities"
        return _is_capabilites_response(_load_into_file(url))
    else:
        # The URL already contains a getCapabilites request but the result was not a correct answer.
        return False