{#
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
#}
{% macro testconn() %}
  <script>
    $("#sqlalchemy_uri").parent()
      .append('<button id="testconn" class="btn btn-sm btn-primary">{{ _("Test Connection") }}</button>');
    $("#testconn").click(function(e) {
      e.preventDefault();
      var url = "/superset/testconn";
      var csrf_token = "{{ csrf_token() if csrf_token else '' }}";

      $.ajaxSetup({
        beforeSend: function(xhr, settings) {
          if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrf_token);
          }
        }
      });

      var data = {};
      const extra = $("#extra").val();
      const encryptedExtra = $("#encrypted_extra").val();
      try{
        data = JSON.stringify({
          uri: $.trim($("#sqlalchemy_uri").val()),
          name: $('#database_name').val(),
          impersonate_user: $('#impersonate_user').is(':checked'),
          extras: extra ? JSON.parse(extra) : {},
          encrypted_extra: encryptedExtra ? JSON.parse(encryptedExtra) : {},
          server_cert: $("#server_cert").val(),
        })
      } catch(parse_error){
        alert("Malformed JSON in the extras field: " + parse_error);
        return false
      }

      $.ajax({
        method: "POST",
        url: url,
        data: data,
        dataType: 'json',
        contentType: "application/json; charset=utf-8"
      }).done(function(data) {
          alert("Seems OK!");
      }).fail(function(error) {
          var respJSON = error.responseJSON;
          var errorMsg = error.responseText;
          if (respJSON && respJSON.error) {
              errorMsg = respJSON.error;
          }
          alert("ERROR: " + errorMsg);
      });
      return false;
    });
  </script>
{% endmacro %}

{% macro expand_extra_textarea() %}
  <script>
    $('#extra').attr('rows', '5');
  </script>
{% endmacro %}

{% macro expand_encrypted_extra_textarea() %}
  <script>
    $('#encrypted_extra').attr('rows', '5');
  </script>
{% endmacro %}

{% macro expand_server_cert_textarea() %}
  <script>
    $('#server_cert').attr('rows', '5');
  </script>
{% endmacro %}
