{#
  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 = {};
      try{
        data = JSON.stringify({
          uri: $.trim($("#sqlalchemy_uri").val()),
          name: $('#database_name').val(),
          impersonate_user: $('#impersonate_user').is(':checked'),
          extras: JSON.parse($("#extra").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!");
          if ($('#tables').length == 0)
            $('body div.container').append('<div id="tables"></div>');
          div = $('#tables')
          div.html('Tables:<br>');
          $.each(data, function(i, d){
            var id = 'tbl_' + d;
            div.append('<span id="' + id + '" style="margin: 0px 10px 10px 0px;" class="btn btn-default">' + d + '</span>')
            $('#' + id).click(function(){window.location = '/tablemodelview/add';})
          });
      }).fail(function(error) {
          var respJSON = error.responseJSON;
          var errorMsg = error.responseText;
          if (respJSON && respJSON.message) {
              errorMsg = respJSON.message;
          }
          alert("ERROR: " + errorMsg);
      });
      return false;
    });
  </script>
{% endmacro %}

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