<%@ Page Title="" Language="C#" MasterPageFile="~/Credentials/Credentials.master" AutoEventWireup="true" CodeFile="ManageAPICredential.aspx.cs" Inherits="ManageAPICredential" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <style type="text/css">
        .dialog .dialog-title .dialog-close {
            float: right;
            margin-right: 6px;
            cursor: pointer;
        }

            .dialog .dialog-title .dialog-close:before {
                content: '\e600';
            }

        .dialog-content table {
            border-collapse: collapse;
            width: 100%;
        }

            .dialog-content table td {
                padding-top: 30px;
            }

                .dialog-content table td.label {
                    width: 130px;
                    text-align: right;
                    padding-right: 10px;
                    line-height: 24px;
                    height: 24px;
                    vertical-align: top;
                }

                .dialog-content table td input,
                .dialog-content table td textarea {
                    border: 1px solid #a9a9a9;
                    width: 200px;
                    height: 18px;
                    padding: 1px;
                }

                    .dialog-content table td input[type="checkbox"] {
                        border: none;
                    }

                .dialog-content table td textarea {
                    height: 100px;
                    max-width: 200px;
                }

        .icon {
            font-family: CalciteWebCoreIcons;
            cursor: default;
        }
    </style>

    <script type="text/javascript">
        var credentialType = "AEMP";
        var credentialList;

        credentialquery = function (method, param, callback, error, nolog) {
            _network.request("Credentials/ManageAPICredential.aspx?tp=ashx", -1, method, param, callback, error, nolog);
        }

        function OnDelete(cr) {
            var cre = cr;
            if (!cre) {
                return;
            }
            showConfirm(GetTextByKey("P_APICRE_DELETETHECREDENTIALTIPS", 'Do you want to delete the credential?'), GetTextByKey("P_APICRE_DELETECREDENTIAL", 'Delete Credential'), function () {
                credentialquery("DeleteApiCredential", cre.ID, function (data) {
                    OnRefresh();
                }, function (err) {
                    showAlert(GetTextByKey("P_APICRE_FAILEDDELETECREDENTIAL", 'Failed to delete this credential.'), GetTextByKey("P_APICRE_DELETECREDENTIAL", 'Delete Credential'));
                });
            });
        }

        function OnAdd() {
            $('.tr_aicredential').hide();
            $('#tr_enabled').hide();
            creid = undefined;
            $('#dialog_apiname').val('').removeAttr("disabled");
            $('#dialog_username').val('');
            $('#dialog_password').val('');
            $('#dialog_apikey').val('');
            $('#dialog_apisecret').val('');
            $('#dialog_apitoken').val('');
            $('#dialog_apitokensecret').val('');
            $('#dialog_enabled').attr('checked', false);
            $('#dialog_credential .dialog-title span.title').text(GetTextByKey("P_APICRE_ADDMANUFACTURE", 'Add Credential'));
            showmaskbg(true);
            $('#dialog_credential')
                .attr('act', 'add')
                .css({
                    'top': (document.documentElement.clientHeight - $('#dialog_credential').height()) / 3,
                    'left': (document.documentElement.clientWidth - $('#dialog_credential').width()) / 2
                })
                .showDialogfixed();
            $('#dialog_urlkey').focus();
        }

        var creid;
        function OnEdit() {
            var cre = grid_dt.source[grid_dt.selectedIndex].Values;
            if (!cre) {
                creid = undefined;
                return;
            }

            $('#tr_enabled').show();
            creid = cre.ID;
            $('#dialog_apiname').val(cre.ApiDefinitionId).attr("disabled", "disabled");
            if (cre.HasUserName) {
                $('#tr_username').show();
                $('#dialog_username').val(cre.UserName);
            }
            else {
                $('#tr_username').hide();
                $('#dialog_username').val('');
            }

            if (cre.HasPassword) {
                $('#tr_password').show();
                $('#dialog_password').val(cre.Password);
            }
            else {
                $('#tr_password').hide();
                $('#dialog_password').val('');
            }

            if (cre.HasApiKey) {
                $('#tr_apikey').show();
                $('#dialog_apikey').val(cre.ApiKey);
            }
            else {
                $('#tr_apikey').hide();
                $('#dialog_apikey').val('');
            }

            if (cre.HasApiSecret) {
                $('#tr_apisecret').show();
                $('#dialog_apisecret').val(cre.ApiSecret);
            }
            else {
                $('#tr_apisecret').hide();
                $('#dialog_apisecret').val('');
            }

            if (cre.HasApiToken) {
                $('#tr_apitoken').show();
                $('#dialog_apitoken').val(cre.ApiToken);
            }
            else {
                $('#tr_apitoken').hide();
                $('#dialog_apitoken').val('');
            }

            if (cre.HasApiTokenSecret) {
                $('#tr_apitokensecret').show();
                $('#dialog_apitokensecret').val(cre.ApiTokenSecret);
            }
            else {
                $('#tr_apitokensecret').hide();
                $('#dialog_apitokensecret').val('');
            }

            $('#dialog_enabled').attr("checked", cre.IsEnabled);
            $('#dialog_credential .dialog-title span.title').text(GetTextByKey("P_APICRE_EDITMANUFACTURE", 'Edit Credential'));
            showmaskbg(true);
            $('#dialog_credential')
                .attr('act', 'edit')
                .css({
                    'top': (document.documentElement.clientHeight - $('#dialog_credential').height()) / 3,
                    'left': (document.documentElement.clientWidth - $('#dialog_credential').width()) / 2
                })
                .showDialog();
            $('#dialog_urlkey').focus();
        }

        function OnDblClick(e) {
            OnEdit();
        }

        function OnRefresh() {
            showloading(true);
            credentialquery("GetAPICredentialDefs", '', function (data) {
                showloading(false);
                credentialList = data;
                showCredentialList(credentialList);
            }, function (err) {
                showloading(false);
            });
        }


        function getAPIDictionaries() {
            credentialquery("GetAPIDictionaries", '', function (data) {
                var types = [];
                types.push($('<option value="-1"></option>'));
                if (data && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var type = data[i];
                        types.push($('<option></option>').prop('selected', i == 0).val(type.Id).text(type.FriendlyName).data('dic', type));
                    }
                } else {
                    types[0].prop('selected', true);
                }

                $('#dialog_apiname').empty().append(types);
            }, function (err) {
            });
        }


        function showCredentialList(data) {
            var rows = [];
            for (var i = 0; i < data.length; i++) {
                var r = data[i];
                var fr = { Values: r };
                rows.push(fr);
            }

            grid_dt.setData(rows);
        }

        var grid_dt;
        function InitGridData() {
            $('#btnEdit').attr("disabled", "disabled");

            grid_dt = new GridView('#credentiallist');
            grid_dt.lang = {
                all: GetTextByKey("P_GRID_ALL", "(All)"),
                ok: GetTextByKey("P_GRID_OK", "OK"),
                reset: GetTextByKey("P_GRID_RESET", "Reset")
            };
            var list_columns = [
                { name: 'ApiName', caption: GetTextByKey("P_APICRE_APINAME", "API Name"), valueIndex: 'ApiName', css: { 'width': 200, 'text-align': 'left' } },
                { name: 'UserName', caption: GetTextByKey("P_APICRE_USERNAME", "User Name"), valueIndex: 'UserName', css: { 'width': 200, 'text-align': 'left' } },
                { name: 'IsEnabled', caption: GetTextByKey("P_APICRE_ENABLED", "Enabled"), valueIndex: 'IsEnabled', css: { 'width': 200, 'text-align': 'left' } },
                { name: 'Edit', caption: "", css: { 'width': 30, 'text-align': 'center' } },
                { name: 'Delete', caption: "", css: { 'width': 30, 'text-align': 'center' } }
            ];
            var columns = [];
            // head
            for (var hd in list_columns) {
                var col = {};
                col.name = list_columns[hd].name;
                col.caption = list_columns[hd].caption;
                col.visible = true;
                col.sortable = true;
                col.width = list_columns[hd].css.width;
                col.align = list_columns[hd].css["text-align"]
                col.key = list_columns[hd].valueIndex;
                if (col.name === "Edit") {
                    col.isurl = true;
                    col.text = "\uf044";
                    col.events = {
                        onclick: function () {
                            OnEdit();
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    }
                    col.attrs = { 'title': GetTextByKey("P_APICRE_EDIT", 'Edit') };
                }
                else if (col.name === "Delete") {
                    col.isurl = true;
                    col.text = "\uf00d";
                    col.events = {
                        onclick: function () {
                            OnDelete(this);
                        }
                    };
                    col.classFilter = function (e) {
                        return "icon-col";
                    };
                    col.attrs = { 'title': GetTextByKey("P_APICRE_DELETE", 'Delete') };
                }
                columns.push(col);
            }
            grid_dt.canMultiSelect = false;
            grid_dt.columns = columns;
            grid_dt.init();
            grid_dt.rowdblclick = OnEdit;

            grid_dt.selectedrowchanged = function (rowindex) {
                var rowdata = grid_dt.source[rowindex];
                if (rowdata) {
                    creid = rowdata.Values.ID;
                }
            }
        }

        function OnDialogOK() {
            var item = {
                'ApiDefinitionId': $('#dialog_apiname').val(),
                'ApiName': $("#dialog_apiname").find("option:selected").text(),
                'UserName': $('#dialog_username').val().replace(/(^\s*)|(\s*$)/g, ''),
                'Password': $('#dialog_password').val(),
                'ApiKey': $('#dialog_apikey').val().replace(/(^\s*)|(\s*$)/g, ''),
                'ApiSecret': $('#dialog_apisecret').val().replace(/(^\s*)|(\s*$)/g, ''),
                'ApiToken': $('#dialog_apitoken').val().replace(/(^\s*)|(\s*$)/g, ''),
                'ApiTokenSecret': $('#dialog_apitokensecret').val().replace(/(^\s*)|(\s*$)/g, ''),
                'IsEnabled': $('#dialog_enabled').attr("checked") == "checked"
            };
            var alerttitle;
            if (creid) {
                item.ID = creid;
                alerttitle = GetTextByKey("P_APICRE_EDITMANUFACTURE", "Edit Credential");
            } else {
                item.ID = "-1";
                item.IsEnabled = true;
                alerttitle = GetTextByKey("P_APICRE_ADDMANUFACTURE", "Add Credential");
            }
            if (!item.ApiName || item.ApiName.length == 0) {
                showAlert(GetTextByKey("P_APICRE_APINAMENOTBEEMPTY", 'API Name cannot be empty.'), alerttitle);
                $('#dialog_apiname').focus();
                return;
            }

            showloading(true);
            var param = JSON.stringify(item);
            param = htmlencode(param);
            credentialquery("UpdateApiCredentialDefs", param, function (data) {
                showloading(false);
                if (data !== 'OK') {
                    showAlert(data, GetTextByKey("P_APICRE_SAVEMANUFACTURE", 'Save Credential'));
                } else {
                    $('#dialog_credential').hideDialog();
                    OnRefresh();
                }
            }, function (err) {
                showloading(false);
                showAlert(GetTextByKey("P_APICRE_FAILEDTOSAVECREDENTIAL", 'Failed to save credential.'), GetTextByKey("P_APICRE_SAVEMANUFACTURE", 'Save Credential'));
            });
        }

        function setInput(dic) {
            $('#tr_username').hide();
            $('#tr_password').hide();
            $('#tr_apikey').hide();
            $('#tr_apitoken').hide();
            $('#tr_apisecret').hide();
            $('#tr_apitokensecret').hide();
            $('#dialog_username').val('');
            $('#dialog_password').val('');
            $('#dialog_apikey').val('');
            $('#dialog_apisecret').val('');
            $('#dialog_apitoken').val('');
            $('#dialog_apitokensecret').val('');
            if (dic) {
                if (dic.ApiUsername) {
                    $('#tr_username').show();
                }
                if (dic.ApiPassword) {
                    $('#tr_password').show();
                }
                if (dic.ApiKey) {
                    $('#tr_apikey').show();
                }
                if (dic.ApiSecret) {
                    $('#tr_apisecret').show();
                }
                if (dic.ApiToken) {
                    $('#tr_apitoken').show();
                }
                if (dic.ApiTokenSecret) {
                    $('#tr_apitokensecret').show();
                }
            }
        }

        $(function () {
            setPageTitle(GetTextByKey("P_APICREDENTIALS", 'API Credentials'), true);
            InitGridData();
            getAPIDictionaries();

            $("#dialog_apiname").change(function () {
                var dic = $("#dialog_apiname").find("option:selected").data("dic");
                setInput(dic);
            })
            $('#dialog_credential').dialog(function () {
                showmaskbg(false);
            });
            OnRefresh();
            $(window).resize(function () {
                $("#credentiallist").css("height", $(window).height() - $("#credentiallist").offset().top - 4);
                grid_dt && grid_dt.resize();
            }).resize();
        });

    </script>
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <div style="min-width: 400px;">
        <div class="page_title" data-lgid="P_APICREDENTIALS">API Credentials</div>
        <div class="function_title">
            <span class="sbutton iconadd" onclick="OnAdd();" data-lgid="P_APICRE_ADD">Add</span>
            <span class="sbutton iconrefresh" onclick="OnRefresh();" data-lgid="P_APICRE_REFRESH">Refresh</span>
        </div>
        <div class="clear"></div>
        <div id="credentiallist"></div>
    </div>

    <div id="mask_bg">
        <div class="loading c-spin"></div>
    </div>
    <div class="dialog" id="dialog_credential" style="display: none; width: 500px;">
        <div class="dialog-title"><span class="title" data-lgid="P_APICRE_ADDMANUFACTURE">Add Credential</span><em class="dialog-close"></em></div>
        <div class="dialog-content" style="padding-left: 50px;">
            <table>
                <tr>
                    <td class="label" data-lgid="P_APICRE_APINAME_COLON">API Name:</td>
                    <td>
                        <select id="dialog_apiname" tabindex="1" style="width: 200px;">
                        </select></td>
                </tr>
                <tr id="tr_username" class="tr_aicredential" style="display: none;">
                    <td class="label" data-lgid="P_APICRE_USERNAME_COLON">User Name:</td>
                    <td>
                        <input type="text" id="dialog_username" maxlength="50" tabindex="1" /></td>
                </tr>
                <tr id="tr_password" class="tr_aicredential" style="display: none;">
                    <td class="label" data-lgid="P_APICRE_PASSWORD_COLON">Password:</td>
                    <td>
                        <input type="password" id="dialog_password" maxlength="50" tabindex="1" /></td>
                </tr>
                <tr id="tr_apikey" class="tr_aicredential" style="display: none;">
                    <td class="label" data-lgid="P_APICRE_APIKEY_COLON">API Key:</td>
                    <td>
                        <input type="text" id="dialog_apikey" maxlength="200" tabindex="1" /></td>
                </tr>
                <tr id="tr_apisecret" class="tr_aicredential" style="display: none;">
                    <td class="label" data-lgid="P_APICRE_APISECRET_COLON">API Secret:</td>
                    <td>
                        <input type="text" id="dialog_apisecret" maxlength="200" tabindex="1" /></td>
                </tr>
                <tr id="tr_apitoken" class="tr_aicredential" style="display: none;">
                    <td class="label" data-lgid="P_APICRE_APITOKEN_COLON">API Token:</td>
                    <td>
                        <input type="text" id="dialog_apitoken" maxlength="200" tabindex="1" /></td>
                </tr>
                <tr id="tr_apitokensecret" class="tr_aicredential" style="display: none;">
                    <td class="label" data-lgid="P_APICRE_APITOKENSECRET_COLON">API Token Secret:</td>
                    <td>
                        <input type="text" id="dialog_apitokensecret" maxlength="200" tabindex="1" /></td>
                </tr>
                <tr id="tr_enabled" style="display: none;">
                    <td class="label" data-lgid="P_APICRE_ENABLED_COLON">Enabled:</td>
                    <td>
                        <input type="checkbox" id="dialog_enabled" style="width: 18px; margin: 0 auto;" tabindex="4" />
                    </td>
                </tr>
            </table>
        </div>
        <div class="dialog-func">
            <input type="button" value="Cancel" data-lgid="P_APICRE_CANCEL" class="dialog-close" tabindex="6" />
            <input type="button" onclick="OnDialogOK();" value="OK" data-lgid="P_APICRE_OK" tabindex="5" />
            <div class="clear"></div>
        </div>
    </div>
</asp:Content>