<?php
/**
 * Copyright © 2012 Alcatel-Lucent.
 *
 * See the NOTICE file distributed with this work for additional information regarding copyright ownership. Licensed 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.
 */


$flow = $this->flow;
/**
 * @var Api $api
 */
$api = $flow->flowScope["api"];
$apiid = $flow->flowScope["apiid"];


$validationErrors = $flow->flowScope["validationErrors"];

$messages = $this->messages;

$contexts = $api->getContexts();
$context = null;
$targetHosts = null;

$tps_warn = "";
$tps_threshold = "";
$tpm_warn = "";
$tpm_threshold = "";

if(!empty($contexts)){
    $context = $contexts[0];
    $targetHosts = $context->getTargetHosts();

    $tps_warn = strval($context->getMaxRateLimitTPSWarning());
    $tps_threshold = strval($context->getMaxRateLimitTPSThreshold());
    $tpm_warn = strval($context->getMaxRateLimitTPMWarning());
    $tpm_threshold = strval($context->getMaxRateLimitTPMThreshold());
}

$auth_noAuth = in_array("noAuth",$api->getAuthentication()->getAuths()) ? true : false;
$auth_basic = in_array("basic",$api->getAuthentication()->getAuths()) ? true : false;
$auth_authKey = in_array("authKey",$api->getAuthentication()->getAuths()) ? true : false;
$auth_wsse = in_array("wsse",$api->getAuthentication()->getAuths()) ? true : false;
$auth_ipWhiteList = in_array("ipWhiteList",$api->getAuthentication()->getAuths()) ? true : false;

$authkey_key="";
if($auth_authKey && $api->getAuthentication()->getAuthKey() !== null){
    $authkey_key = $api->getAuthentication()->getAuthKey();
}

$https = false;
if($api->getHttps() !== null ){
    $https = (boolean)$api->getHttps()->getEnabled();
}

$tlsmode = null;
if($https){
    $tlsmode = $api->getHttps()->getTlsMode();
}
if(empty($tlsmode)){
    $tlsmode = TLSMode::$OneWay;
}

$methods = $api->getAllowedHttpMethods();

$get = in_array("GET", $methods);
$post = in_array("POST", $methods);
$put = in_array("PUT", $methods);
$delete = in_array("DELETE", $methods);

$tdrsenabled = $api->getTdrEnabled();

$advancedOpen = ($api->getStatus() !== Status::$ACTIVE
    || !($auth_noAuth && ! $auth_authKey && ! $auth_basic && ! $auth_ipWhiteList && ! $auth_wsse)
    || $https
    || $tps_threshold !== "-1" || $tps_warn !== "-1"
    || $tpm_threshold !== "-1" || $tpm_warn !== "-1"
    || (!($get && $post && $put && $delete))
    || !empty($api->properties)
    || !empty($api->headerTransformations)
    || $tdrsenabled
    || !empty($api->tdrData->dynamicTdrs)
    || !empty($api->tdrData->staticTdrs));

$relatedProperties = @$flow->flowScope["relatedProperties"];

$apiNameTip = $this->translate("The unique name for this API");
$endpointNameTip = $this->translate("The endpoint name for this API");
$targetHostTip = $this->translate("The target host URI");
$addTargetHostTip = $this->translate("Add additional target host");
$removeTargetHostTip = $this->translate("Remove target host");
$enabledTip = $this->translate("Enable this API");
$disabledTip = $this->translate("Disable this API");
$authTypeNoAuthTip = $this->translate("Don't use authentication with this API");
$authTypeBasicTip = $this->translate("Use basic access (username and password)");
$authTypeAuthKeyTip = $this->translate("Authenticate with key data");
$authTypeWsseTip = $this->translate("Use WS-Security (username and password)");
$authTypeWhitelistTip = $this->translate("Use a list of approved IP addresses");
$usernameTip = $this->translate("Enter a user name");
$passwordTip = $this->translate("Enter a password");
$authKeyTip = $this->translate("Enter key data");
$whitelistTip = $this->translate("Enter a comma-separated list of IPs");
$httpsTip = $this->translate("Select to enforce HTTPS for this API");
$httpsModeOneWayTip = $this->translate("Server authenticates client only");
$httpsModeTwoWayTip = $this->translate("Both server and client perform authentication");
$rateWarningTip = $this->translate("Enter the warning level for this limit");
$rateThresholdTip = $this->translate("Enter the threshold level for this limit");
$httpMethodGetTip = $this->translate("Use HTTP Get with this API");
$httpMethodPostTip = $this->translate("Use HTTP Post with this API");
$httpMethodPutTip = $this->translate("Use HTTP Put with this API");
$httpMethodDeleteTip = $this->translate("Use HTTP Delete with this API");
$tdrsEnabledTip = $this->translate("Enable TDRs for this API");
$tdrsDisabledTip = $this->translate("Disable TDRs for this API");
$saveButtonTip = $this->translate("Click to post and return to API list");
$saveButtonAuthTip = $this->translate("Click to save the API and create Auths for it");

?>

<div class="container">
<?  if(empty($apiid)): ?>
        <h1><? echo $this->translate("Create API")?></h1>
<?  else: ?>
        <h1><? echo $this->translate("Edit API")?></h1>
<?  endif; ?>
<?  if(isset($validationErrors["default"]) && !empty($validationErrors["default"])): ?>
    <div class="warning">
        <p><?=$validationErrors["default"]?></p>
    </div>
<?  endif; ?>
    <form id="form1" class="well form-horizontal" method="post" data-behavior="confirm" action="<?=$flow->flowURI()?>">
        <fieldset>
            <div class="control-group <?=isset($validationErrors["name"])?"error":""?>">
                <label class="control-label" for="input01"><? echo $this->translate("Name")?></label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="input01" name="apiName"
                           rel="tooltip" title="<?=$apiNameTip?>"
                        <?= $api !== null ? 'value="'.$api->getDisplayName().'"' : "" ?>
                        >
                </div>
                <span class="help-inline"><?=@$validationErrors['name']?></span>
            </div>
            <div class="control-group <?=isset($validationErrors["endpoint"])?"error":""?>">
                <label class="control-label" for="input03"><? echo $this->translate("Endpoint")?></label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="input03" name="apiEndpoint"
                           rel="tooltip" title="<?=$endpointNameTip?>"
                        <?= $api !== null ? 'value="'.$api->getEndpoint().'"' : "" ?>
                        >
                </div>
                <span class="help-inline"><?=@$validationErrors['endpoint']?></span>
            </div>
<?          if(count($api->getContexts()) > 1):
                print "<p>" . $this->translate("Only the first context of this api is displayed!") . "</p>";
            endif;
            if($context === null || empty($targetHosts)): ?>
                <div id="targethostGroup">
                    <div class="control-group targethost <?=isset($validationErrors["targethost0"])?"error":""?>" id="targethostGroup0">
                        <label class="control-label" for="targethost0"><? echo $this->translate("Target Host")?></label>
                        <div class="controls">
                            <input type="text" class="input-xlarge" id="targethost0" name="targethost0"
                                   rel="tooltip" title="<?=$targetHostTip?>">
                            <button class="btn newItem" type="targethost" title="<?=$addTargetHostTip?>"
                                rel="tooltip" data-placement="right"><i class="icon-plus"></i></button>
                        </div>
                        <span class="help-inline"><?=@$validationErrors['targethost0']?></span>
                    </div>
                </div>
<?          else:
                $contexts = $api->getContexts();
                /**
                 * @var ApiContext $context
                 */
                $context = $contexts[0];
                /**
                 * @var array(TargetHost) $targetHosts
                 */
                $targetHosts = $context->getTargetHosts();
                $th = $targetHosts[0]; ?>
                <div id="targethostGroup">
                    <div class="control-group targethost <?=isset($validationErrors["targethost0"])?"error":""?>" id="targethostGroup0">
                        <label class="control-label" for="targethost0"><? echo $this->translate("Target Host")?></label>
                        <div class="controls">
                            <input type="text" class="input-xlarge" id="targetHost0" name="targethost0" value="<?=$th->getUrl()?>"
                                   rel="tooltip" title="<?=$targetHostTip?>">
                            <button class="btn newItem" type="targethost" title="<?=$addTargetHostTip?>"
                                    rel="tooltip" data-placement="right"><i class="icon-plus"></i></button>
                        </div>
                        <span class="help-inline"><?=@$validationErrors['targethost0']?></span>
                    </div>
                </div>
<?          $i = 1;
            foreach(array_splice($targetHosts,1) as $th): ?>
                <div class="control-group targethost <?=isset($validationErrors["targethost".$i])?"error":""?>" id="targethostGroup<?=$i?>">
                    <label class="control-label" for="targethost<?=$i?>">&nbsp;</label>
                    <div class="controls">
                        <input type="text" class="input-xlarge" name="targethost<?=$i?>" id="targethost<?=$i?>" value="<?=$th->getUrl()?>"
                               rel="tooltip" title="<?=$this->translate("The target host URI")?>">
                        <button class="btn removeItem" type="targethost" number="<?=$i?>" title="<?=$removeTargetHostTip?>"
                                rel="tooltip" data-placement="right"><i class="icon-minus"></i></button>
                    </div>
                    <span class="help-inline"><?=@$validationErrors['targethost'.$i]?></span>
                </div>
<?              $i = $i + 1;
            endforeach;
        endif; ?>

            <div class="control-group">
                <label class="control-label"><button class="btn" id="showAdvanced"><strong><? echo $this->translate("Advanced")?></strong>
                    <i class="icon-chevron-down advbtn" <?=!$advancedOpen?"":"style=\"display:none\""?>></i><i class="icon-chevron-up advbtn" <?=$advancedOpen?"":"style=\"display:none\""?>></i>
                </button></label>
            </div>
            <div id="advancedSection" class="well well-small second-level" style="<?= $advancedOpen?"":"display:none"?>">
                <div class="control-group">
                    <label class="control-label" for="enabled"><? echo $this->translate("Enabled")?></label>
                    <div class="controls">
                        <div class="btn-group" data-toggle="buttons-radio" id="enabled">
                            <a class="btn api <?=$api->getStatus()===Status::$ACTIVE?"active":""?>"
                               rel="tooltip" title="<?=$enabledTip?>"
                               inputId="apienabled" value="1"><? echo $this->translate("Enabled")?></a>
                            <a class="btn api <?=$api->getStatus()===Status::$ACTIVE?"":"active"?>"
                               rel="tooltip" title="<?=$disabledTip?>"
                               inputId="apienabled" value="0"><? echo $this->translate("Disabled")?></a>
                        </div>
                        <input type="hidden" id="apienabled" name="apienabled" value="<?=$api->getStatus()===Status::$ACTIVE?"1":"0"?>" />
                    </div>
                </div>
                <div class="control-group <?=isset($validationErrors["auth"])?"error":""?>">
                    <label class="control-label" for="authCheck" ><? echo $this->translate("Type")?></label>
                    <div class="controls">
                        <div class="btn-group" data-toggle="buttons-checkbox" id="authCheck">
                            <a class="btn api hiddenValue <?=$auth_noAuth?'active" checked="checked"':'"'?>
                            rel="tooltip" title="<?=$authTypeNoAuthTip?>"
                            inputId="provauth-noAuth" ><? echo $this->translate("No Auth")?></a>
                            <a class="btn api hiddenValue <?=$auth_basic ? 'active" checked="checked"': '"'?>
                            rel="tooltip" title="<?=$authTypeBasicTip?>"
                            inputId="provauth-basic" ><? echo $this->translate("Basic")?></a>
                            <a class="btn api hiddenValue <?=$auth_authKey ? 'active" checked="checked"': '"'?>
                            rel="tooltip" title="<?=$authTypeAuthKeyTip?>"
                            inputId="provauth-authKey" ><? echo $this->translate("Auth Key")?></a>
                            <a class="btn api hiddenValue <?=$auth_wsse ? 'active" checked="checked"': '"'?>
                            rel="tooltip" title="<?=$authTypeWsseTip?>"
                            inputId="provauth-wsse" ><? echo $this->translate("WSSE")?></a>
                            <a class="btn api hiddenValue <?=$auth_ipWhiteList ? 'active" checked="checked"': '"'?>
                            rel="tooltip" title="<?=$authTypeWhitelistTip?>"
                            inputId="provauth-ipWhiteList" ><? echo $this->translate("IP Whitelist")?></a>
                        </div>
                        <input type="hidden" id="provauth-noAuth" name="auth-noAuth" value="<?=$auth_noAuth ? "1": "0"?>" />
                        <input type="hidden" id="provauth-basic" name="auth-basic" value="<?=$auth_basic ? "1": "0"?>" />
                        <input type="hidden" id="provauth-authKey" name="auth-authKey" value="<?=$auth_authKey ? "1": "0"?>" />
                        <input type="hidden" id="provauth-wsse" name="auth-wsse" value="<?=$auth_wsse ? "1": "0"?>" />
                        <input type="hidden" id="provauth-ipWhiteList" name="auth-ipWhiteList" value="<?=$auth_ipWhiteList ? "1": "0"?>" />
                        <span class="help-inline"><?=@$validationErrors['auth']?></span>
                        <p class="help-block"><? echo $this->translate("Choose all that apply.")?></p>
                    </div>
                </div>
            <span id="authkey-key-span" style="display:none;">
                <div id="key" class="control-group <?=(!empty($validationErrors['authkey-key']))?"error":""?>">
                    <label class="control-label" for="authkey-key"><? echo $this->translate("Auth Key Key")?></label>
                    <div class="controls">
                        <input type="text" class="input-xlarge" id="authkey-key" name="authkey-key"
                               rel="tooltip" title="<?=$authKeyTip?>" value="<?=$authkey_key?>"/>
                        <span class="help-inline"><?=@$validationErrors['authkey-key']?></span>
                    </div>
                </div>
            </span>
                <div class="control-group">
                    <label class="control-label" for="httpscheckbox" ><? echo $this->translate("Secured")?></label>
                    <div class="controls">
                        <div class="btn-group" data-toggle="buttons-checkbox" id="httpscheckbox">
                            <a class="btn api hiddenValue <?=$https?'active" checked="checked"':'"'?>
                            rel="tooltip" title="<?=$httpsTip?>"
                            inputId="https"><? echo $this->translate("HTTPS")?></a>
                        </div>
                        <input type="hidden" id="https" name="https" value="<?=$https?"1":"0"?>" />
                    </div>
                </div>
            <span id="https-mode-span" style="display:none;">
                <div id="https-mode-div" class="control-group <?=(!empty($validationErrors['https-mode']))?"error":""?>">
                    <label class="control-label" for="https-mode"><? echo $this->translate("Https Mode")?></label>
                    <div class="controls">
                        <div class="btn-group" data-toggle="buttons-radio" id="https-mode-group">
                            <a class="btn api <?=$tlsmode===TLSMode::$OneWay?"active":""?>" inputId="https-mode"
                               rel="tooltip" title="<?=$httpsModeOneWayTip?>"
                               value="<?=TLSMode::$OneWay?>"><? echo $this->translate("1-Way TLS")?></a>
                            <a class="btn api <?=$tlsmode===TLSMode::$TwoWay?"active":""?>" inputId="https-mode"
                               rel="tooltip" title="<?=$httpsModeTwoWayTip?>"
                               value="<?=TLSMode::$TwoWay?>"><? echo $this->translate("2-Way TLS")?></a>
                        </div>
                        <input type="hidden" class="input-xlarge" id="https-mode" name="https-mode" value="<?=$tlsmode?>"/>
                        <span class="help-inline"><?=@$validationErrors['https-mode']?></span>
                    </div>
                </div>
            </span>

                <div class="control-group">
                    <div class="controls">
                        <span class="label input-small pull-left"><? echo $this->translate("Warning")?></span>
                        <span class="label input-small pull-left"><? echo $this->translate("Threshold")?></span>
                    </div>
                </div>
                <div class="control-group <?=(!empty($validationErrors['tps-warn'])||!empty($validationErrors['tps-threshold']))?"error":""?>">
                    <label class="control-label" for="TPS"><? echo $this->translate("TPS")?></label>
                    <div class="controls">
                        <input type="text" class="input-small" id="TPS" name="tps-warn" value="<?=$tps_warn?>"
                               rel="tooltip" title="<?=$rateWarningTip?>">
                        <input type="text" class="input-small" name="tps-threshold" value="<?=$tps_threshold?>"
                               rel="tooltip" title="<?=$rateThresholdTip?>">
                        <span class="help-inline"><?=@$validationErrors['tps-warn']?></span>
                        <span class="help-inline"><?=@$validationErrors['tps-threshold']?></span>
                    </div>
                </div>
                <div class="control-group <?=(!empty($validationErrors['tpm-warn'])||!empty($validationErrors['tpm-threshold']))?"error":""?>">
                    <label class="control-label" for="TPM"><? echo $this->translate("TPM")?></label>
                    <div class="controls">
                        <input type="text" class="input-small" id="TPM" name="tpm-warn" value="<?=$tpm_warn?>"
                               rel="tooltip" title="<?=$rateWarningTip?>">
                        <input type="text" class="input-small" name="tpm-threshold" value="<?=$tpm_threshold?>"
                               rel="tooltip" title="<?=$rateThresholdTip?>">
                        <span class="help-inline"><?=@$validationErrors['tpm-warn']?></span>
                        <span class="help-inline"><?=@$validationErrors['tpm-threshold']?></span>
                    </div>
                </div>

                <div class="control-group">
                    <label class="control-label" for="methods"><? echo $this->translate("Methods")?></label>
                    <div class="controls">
                        <div class="btn-group" data-toggle="buttons-checkbox" id="methods">
                            <a class="btn api hiddenValue <?=$get?'active" checked="checked"':'"'?>
                            rel="tooltip" title="<?=$httpMethodGetTip?>" inputId="method-get"><? echo $this->translate("GET")?></a>
                            <a class="btn api hiddenValue <?=$post?'active" checked="checked"':'"'?>
                            rel="tooltip" title="<?=$httpMethodPostTip?>" inputId="method-post"><? echo $this->translate("POST")?></a>
                            <a class="btn api hiddenValue <?=$put?'active" checked="checked"':'"'?>
                            rel="tooltip" title="<?=$httpMethodPutTip?>" inputId="method-put"><? echo $this->translate("PUT")?></a>
                            <a class="btn api hiddenValue <?=$delete?'active" checked="checked"':'"'?>
                            rel="tooltip" title="<?=$httpMethodDeleteTip?>" inputId="method-delete"><? echo $this->translate("DELETE")?></a>
                        </div>
                        <input type="hidden" id="method-get" name="method-get" value="<?=$get?"1":"0"?>" />
                        <input type="hidden" id="method-post" name="method-post" value="<?=$post?"1":"0"?>" />
                        <input type="hidden" id="method-put" name="method-put" value="<?=$put?"1":"0"?>" />
                        <input type="hidden" id="method-delete" name="method-delete" value="<?=$delete?"1":"0"?>" />
                        <p class="help-block"><? echo $this->translate("Choose all that apply.")?></p>
                    </div>
                </div>
                <div id="propertyGroup">
                    <? SharedViewUtility::includePropertiesSnippet($api->properties, $validationErrors); ?>
                </div>
                <div id="headerTransGroup">
                    <? SharedViewUtility::includeHeaderTransformationsSnippet($api->headerTransformations, $validationErrors); ?>
                </div>
                <div id="tdrRuleGroup">
                    <div class="control-group" >
                        <label class="control-label" for="tdrsenabled-group"><? echo $this->translate("TDRs")?></label>
                        <div class="controls">
                            <div class="btn-group" data-toggle="buttons-radio" id="tdrsenabled-group">
                                <a class="btn api <?=$tdrsenabled?"active":""?>" inputId="tdrsenabled"
                                   rel="tooltip" title="<?=$tdrsEnabledTip?>" value="1"><? echo $this->translate("Enabled")?></a>
                                <a class="btn api <?=$tdrsenabled?"":"active"?>" inputId="tdrsenabled"
                                   rel="tooltip" title="<?=$tdrsDisabledTip?>" value="0"><? echo $this->translate("Disabled")?></a>
                            </div>
                            <input type="hidden" id="tdrsenabled" name="tdrsenabled" value="<?=$tdrsenabled?"1":"0"?>" />
                        </div>
                    </div>
                </div>
                <span id="tdr-rule-span" style="display:none;">
                    <? SharedViewUtility::includeTdrRulesSnippet($api->tdrData, $validationErrors); ?>
                </span>
            </div>
            <div class="hidden" id="relatedPropertiesTree"><?
                print htmlentities($relatedProperties);
            ?></div>


            <input class="btn" type="submit" value="<? echo $this->translate("Save")?>"
                rel="tooltip" title="<?=$saveButtonTip?>" data-placement="bottom"/>
            <? $showSubmitAndAuth = $auth_authKey === 1 || $auth_basic === 1 || $auth_wsse === 1 || $auth_ipWhiteList === 1; ?>
            <input class="btn" type="submit" value="<? echo $this->translate("Save and Create Auths")?>"
                            rel="tooltip" title="<?=$saveButtonAuthTip?>" data-placement="right"
                            onclick="$('#_faction').val('submitAndAuth');"
                            style="<?=$showSubmitAndAuth?"":"display:none;"?>" id="submitAndAuthButton"/>
            <input type="hidden" value="submit" name="_faction" id="_faction" value="submit" />
        </fieldset>
    </form>
</div> <!-- /container -->