{{define "title"}}
Global Settings
{{end}}

{{define "top_css"}}
{{end}}

{{define "username"}}
{{ .username }}
{{end}}

{{define "page_title"}}
Global Settings
{{end}}

{{define "page_content"}}
<section class="content">
    <div class="container-fluid">
        <!-- <h5 class="mt-4 mb-2">Global Settings</h5> -->
        <div class="row">
            <!-- left column -->
            <div class="col-md-6">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">Wireguard Global Settings</h3>
                    </div>
                    <!-- /.card-header -->
                    <!-- form start -->
                    <form role="form" id="frm_global_settings" name="frm_global_settings">
                        <div class="card-body">
                            <div class="form-group">
                                <label for="endpoint_address">Endpoint Address</label>
                                <div class="input-group input-group">
                                    <input type="text" class="form-control" id="endpoint_address" name="endpoint_address" placeholder="Endpoint Address"
                                        value="{{ .globalSettings.EndpointAddress }}">
                                    <span class="input-group-append">
                                        <button type="button" class="btn btn-success btn-flat" data-toggle="modal"
                                            data-target="#modal_endpoint_address_suggestion"><i
                                                class="nav-icon fas fa-magic"></i> Suggest</button>
                                    </span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="dns_servers" class="control-label">DNS Servers</label>
                                <input type="text" data-role="tagsinput" class="form-control" id="dns_servers" value="">
                            </div>
                            <div class="form-group">
                                <label for="mtu">MTU</label>
                                <input type="text" class="form-control" id="mtu" name="mtu" placeholder="MTU"
                                    value="{{if .globalSettings.MTU}}{{ .globalSettings.MTU }}{{end}}">
                            </div>
                            <div class="form-group">
                                <label for="persistent_keepalive">Persistent Keepalive</label>
                                <input type="text" class="form-control" id="persistent_keepalive"
                                    name="persistent_keepalive" placeholder="Persistent Keepalive"
                                    value="{{if .globalSettings.PersistentKeepalive }}{{ .globalSettings.PersistentKeepalive }}{{end}}">
                            </div>
                            <div class="form-group">
                                <label for="forward_mark">Forward Mark</label>
                                <input type="text" class="form-control" id="forward_mark"
                                    name="forward_mark" placeholder="Forward Mark"
                                    value="{{ .globalSettings.ForwardMark }}">
                            </div>
                            <div class="form-group">
                                <label for="config_file_path">Wireguard Config File Path</label>
                                <input type="text" class="form-control" id="config_file_path"
                                    name="config_file_path" placeholder="E.g. /etc/wireguard/wg0.conf"
                                    value="{{ .globalSettings.ConfigFilePath }}">
                            </div>
                        </div>
                        <!-- /.card-body -->

                        <div class="card-footer">
                            <button type="submit" class="btn btn-success">Save</button>
                        </div>
                    </form>
                </div>
                <!-- /.card -->
            </div>
            <div class="col-md-6">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">Help</h3>
                    </div>
                    <!-- /.card-header -->
                    <div class="card-body">
                        <dl>
                            <dt>1. Endpoint Address</dt>
                            <dd>The public IP address of your Wireguard server that the client will connect to. Click on
                                <strong>Suggest</strong> button to auto detect the public IP address of your server.</dd>
                            <dt>2. DNS Servers</dt>
                            <dd>The DNS servers will be set to client config.</dd>
                            <dt>3. MTU</dt>
                            <dd>The MTU will be set to server and client config. By default it is <code>1420</code>. You might want
                                to adjust the MTU size if your connection (e.g PPPoE, 3G, satellite network, etc) has a low MTU.</dd>
                            <dd>Leave blank to omit this setting in the configs.</dd>
                            <dt>4. Persistent Keepalive</dt>
                            <dd>By default, WireGuard peers remain silent while they do not need to communicate,
                                so peers located behind a NAT and/or firewall may be unreachable from other peers
                                until they reach out to other peers themselves. Adding <code>PersistentKeepalive</code>
                                can ensure that the connection remains open.</dd>
                            <dd>Leave blank to omit this setting in the Client config.</dd>
                            <dt>5. Forward Mark</dt>
                            <dd>Set an <code>fwmark</code> on all packets going out of WireGuard's UDP socket. Default value: <code>0xca6c</code></dd>
                            <dt>6. Wireguard Config File Path</dt>
                            <dd>The path of your Wireguard server config file. Please make sure the parent directory
                                exists and is writable.</dd>
                        </dl>
                    </div>
                </div>
                <!-- /.card -->
            </div>
        </div>
        <!-- /.row -->
    </div>
</section>

<div class="modal fade" id="modal_endpoint_address_suggestion">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Endpoint Address Suggestion</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Following is the list of public and local IP addresses for your consideration.</p>
                <select id="ip_suggestion" class="select2"
                    data-placeholder="Select an IP address" style="width: 100%;">
                </select>
            </div>
            <div class="modal-footer justify-content-between">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-success" id="btn_use_ip" disabled>Use selected IP address</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->
{{end}}

{{define "bottom_js"}}
    <script>
        function submitGlobalSettings() {
            const endpoint_address = $("#endpoint_address").val();
            const dns_servers = $("#dns_servers").val().split(",");
            const mtu = $("#mtu").val();
            const persistent_keepalive = $("#persistent_keepalive").val();
            const forward_mark = $("#forward_mark").val();
            const config_file_path = $("#config_file_path").val();
            const data = {"endpoint_address": endpoint_address, "dns_servers": dns_servers, "mtu": mtu, "persistent_keepalive": persistent_keepalive, "forward_mark": forward_mark, "config_file_path": config_file_path};

            $.ajax({
                cache: false,
                method: 'POST',
                url: '{{.basePath}}/global-settings',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function(data) {
                    $("#modal_new_client").modal('hide');
                    toastr.success('Update global settings successfully');
                },
                error: function(jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        }

        function updateEndpointSuggestionIP() {
            $.getJSON("{{.basePath}}/api/machine-ips", null, function(data) {
                $("#ip_suggestion option").remove();
                $.each(data, function(index, item) {
                    $("#ip_suggestion").append(
                        $("<option></option>")
                            .text(item.ip_address + ' - ' + item.name)
                            .val(item.ip_address)
                    );
                });
                document.getElementById("btn_use_ip").disabled = false;
            });
        }
    </script>
    <script>
        // Wireguard Interface DNS server tag input
        $("#dns_servers").tagsInput({
            'width': '100%',
            'height': '75%',
            'interactive': true,
            'defaultText': 'Add More',
            'removeWithBackspace': true,
            'minChars': 0,
            'placeholderColor': '#666666'
        });

        // Load DNS server to the form
        {{range .globalSettings.DNSServers}}
        $("#dns_servers").addTag('{{.}}');
        {{end}}

        // Global setting form validation
        $(document).ready(function () {
            $.validator.setDefaults({
                submitHandler: function () {
                    submitGlobalSettings();
                }
            });
            $("#frm_global_settings").validate({
                rules: {
                    mtu: {
                        digits: true,
                        range: [68, 65535]
                    },
                    persistent_keepalive: {
                        digits: true
                    },
                    config_file_path: {
                        required: true
                    },
                    forward_mark: {
                        required: false
                    }
                },
                messages: {
                    mtu: {
                        digits: "MTU must be an integer",
                        range: "MTU must be in range 68..65535"
                    },
                    persistent_keepalive: {
                        digits: "Persistent keepalive must be an integer"
                    },
                    config_file_path: {
                        required: "Please enter WireGuard config file path"
                    }
                },
                errorElement: 'span',
                errorPlacement: function (error, element) {
                    error.addClass('invalid-feedback');
                    element.closest('.form-group').append(error);
                },
                highlight: function (element, errorClass, validClass) {
                    $(element).addClass('is-invalid');
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).removeClass('is-invalid');
                }
            });
        });

        // Endpoint IP suggestion modal event
        $(document).ready(function () {
            $("#modal_endpoint_address_suggestion").on('shown.bs.modal', function (e) {
                updateEndpointSuggestionIP();
            });
        });

        // Use selected IP address from suggestion form
        $(document).ready(function () {
            $("#btn_use_ip").click(function () {
                const ip = $("#ip_suggestion").select2('val');
                $("#endpoint_address").val(ip);
                $("#modal_endpoint_address_suggestion").modal('hide');
            });
        });
    </script>
{{end}}