<style>
  .inactive-serv{
    font-weight: bold;
    color: red;
    font-size: 1.5em;
    vertical-align: middle;
    padding-left: 0.2em;
  }
  .green_text{
    color: green;
  }
  .red_text{
    color: red;
  }
</style>
<style type="text/css">
  ul.no_list_style li{
    list-style: none;
  }
  ul.no_list_style li label {
    font-weight: bold;
  }
  #info_texts{
    white-space: pre;
  }
</style>
<table class="table main-list default footable-loaded">
  <thead>
    <tr>
      <th>Sites amount</th>
      <th>Server name</th>
      <th>IP</th>
      <th>Port</th>
      <th>Certbot</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <% @site_servers.each do |site_server|%>
      <tr>
        <td>
          <p>
            Active: <%=SiteConstruct.where(:hidden.ne=> true,:server_type => site_server.server_name,:status=>"finish").count %><br>
            Closed: <%=SiteConstruct.where(:hidden.ne=> true,:server_type => site_server.server_name,:status=>"closed").count %><br>
            Not yet installed: <%=SiteConstruct.where(:hidden.ne=> true,:server_type => site_server.server_name,:status=>"").count %><br>
            Production: <%=SiteConstruct.where(:hidden.ne=> true,:server_type => site_server.server_name,:rails_env=>"production",:status=>"finish").count %><br>
            Development: <%=SiteConstruct.where(:hidden.ne=> true,:server_type => site_server.server_name,:rails_env.in=>["development",nil],:status=>"finish").count %><br>
          </p>
        </td>
        <td><%=site_server.server_name%><%= '<span class="inactive-serv" title="inactive">X</span>'.html_safe if !(site_server.active) %></td>
        <td><%=site_server.ip%></td>
        <td><%=site_server.port%></td>
        <td>
          <% if site_server.has_certbot%>
          <span class="green_text"><%= t("client_management.alreay_install") %></span>
          <% if site_server.active %>
            <span><a class="btn btn-success install_certbot_certs" title="<%= t("client_management.install_certbot_certificates_in_batches") %>" data-id="<%=site_server.id.to_s%>"><%= t("client_management.install_certbot_certificates_in_batches") %></a></span>
          <% end %>
          <% else %>
          <span class="red_text"><%= t("client_management.not_install") %></span>
          <% if site_server.active %>
            <span><a class="btn btn-success install_certbot" title="Install certbot" data-name="<%=site_server.server_name%>">Install certbot</a></span>
          <% end %>
          <% end %>
        </td>
        <td>
          <% if site_server.need_update_site_ids.count != 0 %>
          <a class="btn btn-primary update_nginx_settings" href="javascript:void(0)" data-key="<%=site_server.server_name%>" style="background: blueviolet;"><%=t("client_management.update_nginx_settings")%></a>
          <% end %>
          <a class="btn btn-info" href = "<%= admin_site_panel_edit_server_info_path+"?id=#{site_server.id.to_s}" %>"><%=t(:edit)%></a>
          <a class="btn btn-danger" href = "#" onclick="if(window.confirm('Do you really want to delete <%=site_server.server_name%>?')) { window.location.href = '<%= admin_site_panel_edit_server_info_path+"?id=#{site_server.id.to_s}&type=delete" %>';}"><%=t(:remove)%></a>
          <a class="btn btn-primary" href = "<%= admin_site_panel_sites_list_path+"?server_name=#{site_server.server_name}" %>"><%= t('client_management.see_sites') %></a>
          <a class="btn btn-success" href = "<%= backup_setting_admin_site_panel_path(site_server) %>"><%= t('client_management.backup_setting') %></a>
          <a class="btn btn-dark btn-inverse detect_sites" href="javascript:void(0)" data-key="<%=site_server.server_name%>">Detect sites</a>
          <a title="<%=t('client_management.super_manager_management')%>" class="btn btn-primary super_manager_management" href="<%=super_manager_management_admin_site_panel_path(:id=>site_server.id) %>"><%=t('client_management.super_manager_management')%></a>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>
<div class="bottomnav clearfix">
  <div class="pagination pagination-centered"><%=paginate(@site_servers)%></div>
  <a class="btn btn-dark btn-inverse pull-right see_infos" href="javascript:void(0)" data-key="detect_sites">See detect infos</a>
  <a class="btn btn-primary pull-right see_infos" href="javascript:void(0)" data-key="execing_commands">See exec infos</a>
  <a class="btn btn-primary pull-right" href="<%=admin_site_panel_edit_server_info_path+"?type=create"%>"><%=t(:add)%></a>
  <a class="btn btn-dark btn-inverse pull-right detect_sites" href="javascript:void(0)">Detect sites</a>
  <a id="exec_commands" class="btn btn-primary pull-right" href="javascript:void(0)">Exec commands</a>
</div>
<script type="text/javascript">
  $(document).on("change", "input[data-key=\"{{create_super_manager}}\"]", function() {
    if ($(this).prop('checked')){
      $('#super_manager_div').show()
    }else{
      $('#super_manager_div').hide()
    }
  });
  $(document).on("click", ".select_all_server_name_checkbox", function(){
    $('.server_name_checkbox').prop('checked', true);
  });
  $(document).on("click", ".deselect_all_server_name_checkbox", function(){
    $('.server_name_checkbox').prop('checked', false);
  });
  var close_info = false;
  var timeout_id;
  var status_relation = {"starting":"<span style=\"color: skyblue;\">starting</span>","execing":"<span style=\"color: skyblue;\">execing</span>","detecting":"<span style=\"color: skyblue;\">detecting</span>","error":"<span style=\"color: red;\">error</span>","finish": "<span style=\"color: darkseagreen;\">finish</span>","closed":"<span style=\"color: red;\">closed</span>"};
  var need_close_info = false;
  function show_exec_commands_block(server_names){
    if($("#exec-commands-dialog-confirm").length == 0){
      var built_in_commands = "<hr style='clear: both;'/><div><ul class='no_list_style'>"
      <% render :partial => "get_commands_list" %>
      var command_trans = <%= @command_trans.to_json.html_safe %>;
      Object.keys(command_trans).forEach(function(k){
        built_in_commands += "<li><label><input class='built_in_commands' type='checkbox' data-key='{{"+ k +"}}'>" + command_trans[k] + "</label></li>"
      })
      built_in_commands += "</ul></div>"
      $("#main-wrap").before("<div id='exec-commands-dialog-confirm' title='Commands to Exec'>"+
                    "<div style='clear:both;'></div><div id='server_names_block'></div>"+
                    built_in_commands+
                    "<div style=\"display: none;\" id=\"super_manager_div\"><input type=\"text\" placeholder=\"account\" name=\"account\"><br><input type=\"password\" placeholder=\"password\" name=\"password\" minlength=\"8\"></div>"+"<textarea style='height: 200px;width: 100%;' id='commands_area'></textarea>"+
                    "</div>");
    };
    $( "#exec-commands-dialog-confirm" ).dialog({
      resizable: true,
      minHeight: 300,
      maxHeight: 400,
      modal: true,
      width: '80%',
      open: function(){
        $(this).parent().css("top",$(document).height() - $(window).height() + "px");
      },
      close: function(){$( this ).dialog( "close" );},
      buttons: {
      "<%= t(:submit) %>": function(){$( this ).dialog( "close" );exec_commands()},
      }
    });
    $("#server_names_block").html($.map(server_names,function(server_name){
      return "<input style='float: left;' class='server_name_checkbox' type='checkbox' id='server_name_"+server_name+"'><label style='float: left;' for='server_name_"+server_name+"'>"+server_name+"</label>"
    }).join('') + "<div style='clear: both;'></div><a class=\"btn btn-small select_all_server_name_checkbox\"><%=t('client_management.select_all')%></a><a class=\"btn btn-small deselect_all_server_name_checkbox\"><%=t('client_management.deselect_all')%></a>");
  }
  function exec_commands(){
    var commands = "";
    var built_in_commands_selected = [];
    $("input.built_in_commands:checked").each(function(i,v){
      built_in_commands_selected.push($(v).data("key"));
    })
    commands += built_in_commands_selected.join("////");
    commands += $('#commands_area').val().replace(/(\r\n|\n)/g,"////");
    var server_names = [];
    var $els = $(".server_name_checkbox");
    for(var i = 0; i < $els.length; i++){
      if($els.eq(i).prop("checked")){
        server_names.push($("label[for='"+$els.eq(i).attr('id')+"']").text().trim());
      }
    }
    $.post("<%=admin_site_panel_edit_site_path%>",{'server_names':server_names,'commands':commands,'account': $('input[name="account"]').val(),'password': $('input[name="password"]').val()}).done(function(){
     show_infos_dialog("execing_commands");
    });
  }
  function see_infos(key){
    key = key || "";
    if(!close_info){
      var request = $.post("<%=admin_site_panel_edit_server_info_path%>",{"type":'see_infos',"key":key});
      request.done(function(data){
        var infos = request.responseJSON.infos;
        var status = request.responseJSON.status;
        if($("#info_texts").length == 0)
          return infos.join("\n")
        else{
          if(status == "")
            var status_text = "not yet create";
          else
            var status_text = status_relation[status];
          if(!status_text){
            status_text = "<span style=\"color: skyblue;\">"+status+"</span>";
          }
          $("#info_texts").html(status_text+"<div style='clear:both;'></div>"+infos.join("\n"));
          msg_end.scrollIntoView();
          if(need_close_info && status != 'execing'){
            close_info = true;
            window.setTimeout(function(){
              if(window.confirm("<%=t('client_management.finished_reload_page')%>")){
                window.location.reload();
              }
            },1000);
          }else{
            if(status == 'execing'){
              need_close_info = true;
            }
            timeout_id = window.setTimeout(see_infos(key),1000);
          }
        }
      })
    }else{
      window.clearTimeout(timeout_id);
    }
  };
  function show_infos_dialog(key){
      key = key || "";
      close_info = true;
      window.clearTimeout(timeout_id);
      close_info = false;
      if($("#dialog-confirm").length == 0){
        $("#main-wrap").before("<div id='dialog-confirm' title='site infos'>"+
                      "<div style='clear:both;'></div><div id='info_texts'>"+see_infos(key)+"</div><div id='msg_end' style='height:0px; overflow:hidden'></div>"+
                      "</div>");
      }else{
        see_infos(key);
      };
      $( "#dialog-confirm" ).dialog({
        resizable: true,
        minHeight: 100,
        maxHeight: 400,
        width: '80%',
        modal: true,
        open: function(){
          $(this).parent().css("top",$(document).height() - $(window).height() + "px");
        },
        close: function(){
          close_info = true;
          need_close_info = false;
        },
        buttons: {
          "<%= t('client_management.confirm') %>": function(){
            $( this ).dialog( "close" );
          },
          "stop update": function(){
            close_info = true;
          }
        }
      });
    }
  $(document).ready(function(){
    $(".detect_sites").off('click').on('click',function(){
      var key = $(this).data("key");
      if( key == undefined)
        key = "";
      $.post("<%=admin_site_panel_edit_server_info_path%>",{"type":"detect_sites","key":key}).done(function(){
        show_infos_dialog("detect_sites");
      })
    });
    $(".update_nginx_settings").off('click').on('click',function(){
      var key = $(this).data("key");
      if( key == undefined)
        key = "";
      $.post("<%=admin_site_panel_update_nginx_settings_path%>",{"key":key}).done(function(){
        show_infos_dialog("update_multiple_nginx_setting");
      })
    });
    $("#exec_commands").off('click').on('click',function(){
      //show_exec_commands_block(server_names)
      $.post("<%=admin_site_panel_edit_server_info_path%>",{"type":"get_server_names"}).done(function(server_names){
        var server_names = Array.isArray(server_names) ? server_names : [];
        show_exec_commands_block(server_names);
      })
    });
    $(".see_infos").off('click').on('click',function(){
      var key = $(this).data("key")
      if(key == undefined)
        key = ""
      $.post("<%=admin_site_panel_edit_server_info_path%>",{"type":"see_infos","key":key}).done(function(){
        show_infos_dialog(key);
      })
    });
    $(".install_certbot").off("click").on("click",function(){
      var server_name = $(this).data("name");
      if( server_name == undefined)
        server_name = "";
      $.post("<%=admin_site_panel_install_certbot_path%>",{"server_name":server_name}).done(function(){
        show_infos_dialog("install_certbot");
      })
    })
    $(".install_certbot_certs").off("click").on("click",function(){
      var id = $(this).data("id");
      $.post("<%=admin_site_panel_edit_site_path%>",{'id': id,'type':'select_cert', 'is_server': true}).done(function(response){
        show_infos_dialog("batch_install_certs");
      });
    })
  })
</script>