<!-- Macro for toggle button to display _output fields of checks -->
{% macro toggle_output(output, target, title) %}
    <button class="commonstyle own-line btn btn-default btn-sm" data-toggle="collapse" data-target={{'#' + target}}>
        {{title}}
    </button>
    <div class="collapse" id={{target}}>
        <pre class="commonstyle"><code>{{output}}</code></pre>
    </div>
{% endmacro %}

<!-- Macro for one check result -->
{% macro check_result(check, title, environment, is_admin, context) %}
    <!-- check-result is a reserved class name -->
    {% set check_summary = check['summary'] if check.get('summary') != None else '' %}
    <div class="{{'check-' + check['status'].lower() + ' boxstyle'}} check-result">
        <h5 style='margin:10px 5px 10px 5px;'}}>
            <div class='row'>
                <div class="col-sm-4">
                    <div class="col-sm-1" style="padding:0;" align="center">
                        {% if check.get('assc_action_status')%}
                            <span class="{{'action-icon assc-action-' + check['assc_action_status'].lower()}}"></span>
                        {% endif %}
                    </div>
                    <div class="col-sm-11" style="padding:0;">
                        <a class="title-hover" data-toggle="collapse" id={{'toggle-' + environment + '-' + check['name']}} href={{'#' + environment + '-' + check['name']}}>
                            {{title}}
                        </a>
                    </div>
                </div>
                <div class="col-sm-6">
                    <span class="opacity-transition" id={{'summary-' + environment + '-' + check['name']}} style="font-weight:350;">
                        {{check_summary[:77] + '...' if (check_summary and check_summary|length > 80) else check_summary}}
                    </span>
                </div>
                <div class="col-sm-2 pull-right">
                    <span style="font-weight:350;">
                        {{check.get('local_time', 'No timestamp')}}
                    </span>
                </div>
            </div>
        </h5>
        <div class="collapse collapse-div commonstyle container-fluid" id={{environment + '-' + check['name']}}>
            <hr style="margin:0px 0px 8px 0px; border-top:1px solid #ccc;">
            <div class='row'>
                <div class="col-sm-9">
                    {% if check.get('description') %}
                        <div class="commonstyle own-line">{{check['description']}}</div>
                    {% endif %}
                    {% if check.get('ff_link') %}
                        <a href={{check['ff_link']}} target="_blank" class="commonstyle own-line">{{check['ff_link']}}</a>
                    {% endif %}
                    {% if check.get('brief_output')%}
                        {{toggle_output(check['brief_output'], environment + '-' + check['name'] + '-brief', 'Toggle brief output')}}
                    {% endif %}
                    {% if check.get('full_output')%}
                        {{toggle_output(check['full_output'], environment + '-' + check['name'] + '-full', 'Toggle full output')}}
                    {% endif %}
                    {% if check.get('admin_output') and is_admin %}
                        {{toggle_output(check['admin_output'], environment + '-' + check['name'] + '-admin', 'Toggle admin output')}}
                    {% endif %}
                    {% if check.get('assc_action') %}
                        {{toggle_output(check['assc_action'], environment + '-' + check['name'] + '-assc-action', 'Toggle associated action')}}
                    {% endif %}
                    {% if check.get('action') and is_admin %}
                        <form class="commonstyle own-line" action={{context + "view_run/" + environment + '/' + check['action'] + '/action'}} method="GET">
                            <input type="hidden" name="check_name" value={{check['name']}} />
                            <input type="hidden" name="called_by" value={{check['kwargs']['uuid']}} />
                            {% if not check.get('allow_action') %}
                                <button id={{"action-" + check['name'] + "-" + check['kwargs']['uuid']}} class="btn btn-warning btn-sm" disabled>
                                    {{' '.join(check['action'].split('_')).title()}}
                                </button>
                            {% else %}
                                <button id={{"action-" + check['name'] + "-" + check['kwargs']['uuid']}} class="btn btn-warning btn-sm" onclick="{{"return confirm_action('" + check['name'] + "-" + check['kwargs']['uuid'] + "', '" + check.get('action_message', 'Confirm run?') + "');" | safe}}" type="button">
                                    {{' '.join(check['action'].split('_')).title()}}
                                </button>
                            {% endif %}
                        </form>
                        <div id={{"action-message-" +check['name'] + "-" + check['kwargs']['uuid']}}></div>
                    {% endif %}
                </div>
                <div class="col-sm-3 pull-right" style="text-align: right;">
                    <a class="commonstyle own-line" target="_blank" href={{context + 'history/' + environment + '/' + check['name']}}>
                        Result History
                    </a>
                    {% if check.get('action_history') %}
                      <a class="commonstyle own-line" target="_blank" href={{context + 'history/' + environment + '/' + check['action_history']}}>
                        Action History
                      </a>
                    {% endif %}
                    {% if check.get('kwargs') %}
                        <form action={{context + 'view_run/' + environment + '/' + check['name'] + '/check'}} method="GET" target="_blank">
                            {% for kwarg in check['kwargs'] %}
                                {% if kwarg not in ['uuid', '_run_info', 'runtime_seconds', 'queue_action'] %}
                                    <span style="font-weight: bold; margin-right: 5px">{{kwarg}}</span>
                                    {% if is_admin %}
                                        <input style="width: 35%;" type="text" name={{kwarg}} value="{{check['kwargs'][kwarg]}}" /><br>
                                    {% else %}
                                        <span>{{check['kwargs'][kwarg]}}</span><br>
                                    {% endif %}
                                {% elif kwarg == 'queue_action' %}
                                    {% if check.get('action') %}
                                        <span style="font-weight: bold; margin-right: 5px">{{kwarg}}</span>
                                        {% if is_admin %}
                                            <input style="width: 35%;" type="text" name={{kwarg}} value="{{check['kwargs'][kwarg]}}" /><br>
                                        {% else %}
                                            <span>{{check['kwargs'][kwarg]}}</span><br>
                                        {% endif %}
                                    {% endif %}
                                {% endif %}
                            {% endfor %}
                            {% if is_admin %}
                                <button style="margin-top: 5px;" class="btn btn-default btn-sm" type="submit">
                                    Queue check
                                </button>
                            {% endif %}
                        </form>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
{% endmacro %}

<!-- Main body template. Define the base template, <style> and <script> here -->
<!DOCTYPE html>
<html class="html-scroll">
<head>
    <meta charset="utf-8">
    <title>Foursight</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional Bootstrap theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <!-- Update with data soon -->
    <link rel="shortcut icon" type="image/x-icon" href={{favicon}}>
    <!-- Get variables needed within js from jinja -->

    <style type="text/css">
    .html-scroll {
        overflow-y: scroll;
    }
    .container {
        max-width: 1900px;
        padding-top: 10px;
    }
    .control-form {
        display: inline;
        margin-right: 20px;
        margin-top: -8px;
    }
    .boxstyle {
        border: 1px solid #ccc;
        margin-bottom: 5px;
        border-radius: 8px;
        padding: 0px 0px 0px 0px;
    }
    .group-boxstyle {
        border: 1px solid #ccc;
        margin-bottom: 5px;
        border-radius: 8px;
        padding: 0px 0px 0px 0px;
        background-color: #f8f8f8;
    }
    .group-boxstyle:hover {
        background-color: #f2f2f2;
    }
    .login-w-hover {
        border: 1px solid #ccc;
        border-radius: 8px;
        background-color: #f8f8f8;
        font-weight: 350;
    }
    .login-w-hover:hover {
        background-color: #d9d9d9;
    }
    .commonstyle {
        margin: 0px 10px 5px 10px;
    }
    .collapse-div{
        overflow: hidden;
        clear: both;
    }
    .own-line {
        display: block;
    }
    .in-line{
        display: inline-block;
    }
    .action-icon {
        height: 11px;
        width: 11px;
        border-radius: 50%;
        display: inline-block;
    }
    .assc-action-done {
        background-color: #55aa57;
    }
    .assc-action-fail {
        background-color: #b84947;
    }
    .assc-action-pend {
        background-color: #e7c418;
    }
    .assc-action-ready {
        background-color: #b6b5b5;
    }
    .check-pass, .check-done {
        background-color: #dff0d8;
        color: #3c763d;
    }
    .check-warn, .check-pend {
        background-color: #fcf8e3;
        color: #8a6d3b;
    }
    .check-fail {
        background-color: #f2dede;
        color: #a94442;
    }
    .check-error {
        background-color: #fbdcbd;
        color: #b75c00;
    }
    .check-ignore {
        display: none;
    }
    .center-element {
        text-align: center;
    }
    .opacity-transition {
        -webkit-transition: opacity 0.5s;
        transition: opacity 0.5s;
    }
    .title-image-hover, .title-image-hover:visited, .title-image-hover:active {
        text-decoration: none;
        opacity: 0.7;
    }
    .title-image-hover:hover, .title-image-hover:focus {
        text-decoration: none;
        opacity: 1.0;
    }
    .title-hover, .title-hover:visited, .title-hover:active {
        color: inherit;
    }
    .title-hover:hover, .title-hover:focus{
        text-decoration: none;
        color: #000;
    }
    .top-level-list {
        padding: 0px;
    }
    .no-border {
        border: none;
    }
    li {
        list-style-type: none;
        padding: 0;
        margin: 0;
    }
    dl {
        margin-bottom: 0px;
    }
    dd {
        margin-left: 20px;
        margin-bottom: 5px;
    }
    </style>
</head>
<body>
    <div class="container">
        <h3 class="center-element">
            <a class="title-image-hover opacity-transition" href={{context + 'view/' + env}}>
                <img class="in-line" alt="FS logo" style="margin:-5px 2px 0px 0px;" height="30" src={{favicon}}></img>
            </a>
            <span>{{'Foursight'}}</span>
        </h3>
        {% if load_time %}
            <h5 class="center-element">
                <span>{{'Loaded on ' + load_time}}</span>
            </h5>
        {% endif %}
        {% if is_admin %}
            <h5 class="center-element">
                <span>{{'Currently logged in as admin'}}</span> <br />
                <span>{{'Deployment Stage is ' + stage + ''}}</span>
            </h5>
        {% else %}
            <h5 class="center-element">
                <span>{{'Not logged in as admin'}}</span>
                <button class="login-w-hover in-line" onclick="create_redir_cookie(); lock.show();">Log in</button>
            </h5>
        {% endif %}
        {% if running_checks != '0' or queued_checks != '0' %}
            <div class='center-element'>
                <span style='margin-right:10px; color:#777'>
                    {{'Running: ' + running_checks}}
                </span>
                <span style='color:#777'>
                    {{'Queued: ' + queued_checks}}
                </span>
            </div>
        {% endif %}
        <div id="content">{% block content %}{% endblock %}</div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script src="https://cdn.auth0.com/js/lock/10.24.1/lock.min.js"></script>
    <script type="text/javascript">
      // set cookie containing the location we were at when we tried to Login
      // this cookie is re-loaded at /callback and parsed for the url, which
      // it redirects to upon finishing authentication
      function create_redir_cookie() {
        var expr = new Date();
        expr.setFullYear(expr.getFullYear() + 1);
        document.cookie = "redir=" + window.location.href + "; path=/; expires=" + expr.toUTCString();
      }
    </script>
    <script type="text/javascript">
        var domain = "{{domain}}";
        var context = "{{context}}";
        var lock = new Auth0Lock('DPxEwsZRnKDpk0VfVAxrStRKukN14ILB', 'hms-dbmi.auth0.com', {
            auth: {
                redirectUrl: 'https://' + domain + context + 'callback/',
                responseType: 'code',
                sso: false,
                params: {scope: 'openid email', prompt: 'select_account'}
            },
            socialButtonStyle: 'big',
            languageDictionary: { title: "Log in" },
            theme: { logo: "{{favicon}}" },
            allowedConnections: ['github', 'google-oauth2']
        });
    </script>
    <script type="text/javascript">
        function collapse_group(e, id){
            // Do not trigger collapse if click is on or a child of a check-result
            var isCheck = $(e.target).hasClass("check-result")
            var parents = $(e.target).parents(".check-result");
            if(!isCheck && parents.length === 0){
                $('#' + id).collapse('toggle');
            }
        }
    </script>
    <script type="text/javascript">
        function confirm_action(uuid, message){
            var actionMessage = document.getElementById("action-message-" + uuid);
            actionMessage.innerHTML = '<pre class="commonstyle"><code>' + message + '</code></pre>';
            var actionButton = document.getElementById("action-" + uuid);
            actionButton.classList.remove('btn-warning');
            actionButton.classList.add('btn-danger');
            actionButton.onclick = null;
            actionButton.disabled = true;
            setTimeout(function(){
                actionButton.disabled = false;
                actionButton.type = "submit";
            },1000);
        }
    </script>
    <script>
        // Toggle opacity of a check result summary when the anchor to open/close result is used
        $(document).ready(function() {
            $('.title-hover').click(function(){
                var anchorId = $(this).attr("id");
                var variablePart = anchorId.replace("toggle-","");
                var summaryEle = $('#summary-'+variablePart);
                if (summaryEle.css('opacity') == 0){
                    summaryEle.css({ opacity: 1 });
                }else{
                    summaryEle.css({ opacity: 0 });
                }
            });
        });
    </script>
    {% block script %}{% endblock %}
</body>
</html>
