<?
/**
 * 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.
 */

require_once APPLICATION_PATH . '/models/Action.class.php';
/**
 * View File for the Policy form
 */
/**
 * @var Flow
 */
$flow = $this->flow;

/**
 * @var Policy $policy
 */
$policy = $flow->flowScope['policy'];
$validationErrors = @$flow->flowScope['validationErrors'];

/*
$policy = empty($this->policy) ? new Policy() : $this->policy;
*/

$id = $policy->getId();
$authBucketArray = $policy->getAuthIds();
$authBucketId = (count($authBucketArray) > 0) ? $authBucketArray[0]->getId() : "";
$contexts = $policy->getContexts();
$context = empty($contexts) ? new Context() : (count($contexts) > 0 ? $contexts[0] : new Context());

$this->apis = $flow->flowScope['apis'];
$this->auths = $flow->flowScope['auths'];

if (empty($this->apis)) {
    // This should probably be an error condition; use empty array to avoid problems
    $this->apis = array();
}
if (empty($this->auths)) {
    // This should probably be an error condition; use empty array to avoid problems
    $this->auths = array();
}
/*
$validationErrors = $this->validationErrors; //@$flow->flowScope['validationErrors'];
$id = $policy->getId();
if (!isset($this->isNew)) { $this->isNew = empty($id); }
*/

$this->isNew = $flow->flowScope['isNew'];

$formAction = $this->isNew ? "/policy/create" : "/policy/".$id;

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

$idTip = $this->isNew ? $this->translate("Enter a unique ID for this Policy") :
    $this->translate("The ID for an existing Policy cannot be changed");
$selectApiTip = $this->translate("Select one or more APIs");
$selectAuthTip = $this->translate("Select one or more Auths");
$rateActionTip = $this->translate("Choose an action for when this limit is reached");
$rateWarningTip = $this->translate("Enter the warning level for this limit");
$rateThresholdTip = $this->translate("Enter the threshold level for this limit");
$submitButtonTip = $this->translate("Post and return to Policy list");

?>
<div class="container">
    <h1><?php if ($this->isNew) {echo $this->translate("Create Policy");} else {echo $this->translate("Edit Policy");} ?></h1>
    <? if(!empty($validationErrors['default'])):?>
    <div class="control-group error">
        <span class="help-inline"><? echo $this->translate("Server Error")?>: <?=$validationErrors['default']?></span>
    </div>
    <? endif; ?>
    <? if(!empty($this->messages)): ?>
    <div class="control-group success">
                <span class="help-block">
                    <? foreach ($this->messages as $message): ?>
                    <?=$message?>
                    <? endforeach ?>
                </span>
    </div>
    <? endif ?>
    <form class="well form-horizontal" action="<?php echo $formAction ?>" method="POST">
        <fieldset>
            <div class="control-group">
                <label class="control-label" for="policy_id"><? echo $this->translate("ID")?></label>
                <div class="controls">
                    <input type="text" class="input-xlarge" id="policy_id" name="policy_id"
                           rel="tooltip" title="<?=$idTip?>"
                           value="<?php echo $id ?>"<?php if (!$this->isNew) {echo ' readonly="readonly"';} ?> />
                    <span class="help-inline"><?=@$validationErrors['policyId']?></span>
                </div>
            </div>
            <div class="control-group">
                <label class="control-label"><? echo $this->translate("APIs")?></label>
                <div class="controls btn-group-vertical" style="margin-left: 20px">
                    <div class="well second-level well-small">
                        <input type="text" filterType="Api" class="filter-field filterMe" id="filterApi" style="margin-bottom: 10px" rel="tooltip" title="<?//=$idTip?>" value="" placeholder="<?=$this->translate("Filter APIs by...")?>" />
                        <div id="api-group">
                            <div class="btn-group btn-group-vertical pull-left" id="selectApi">
                                <?php foreach ($this->apis as $api): ?>
                                <?php $policyApiIds = $policy->getApiIds();
                                if (!empty($policyApiIds)) {
                                    foreach ($policyApiIds as $policyApiId) {
                                        $a = 0;
                                        if ($policyApiId === $api->id) { $selectedAPI[] = $api; $a = 1; break; }
                                    }
                                    if ($a == 1)continue; //if the api is already selected, we don't want it to appear in the selectable list
                                } ?>
                                <a class="btn moveSelected filterApi" rel="tooltip" data-placement="left" title="<?=$api->displayName . " /" . $api->endpoint?>"
                                   type="api" style="text-align:left" name="<?=$api->id;?>" id="<?=$api->displayName?>" filter="<?=$api->id." ".$api->endpoint." ".$api->displayName?>">
                                    <div class="ellipsis pull-left" style="width:45%"><strong><?=$api->displayName?></strong></div>
                                    <div class="ellipsis" style="padding-left: 5px;width:49%"><i>/<?=$api->endpoint?></i></div></a>
                                <?php endforeach ?>
                            </div>
                            <div class="btn-group btn-group-vertical pull-right">
                                <div class="well well-small third-level" style="min-height: 180px; margin-bottom:0" id="selectedApi">
                                    <? if(!empty($selectedAPI)){ foreach($selectedAPI as $api):?>
                                    <a class="btn moveSelected filterApi" rel="tooltip" data-placement="left" title="<?=$api->displayName . " /" . $api->endpoint?>"
                                       type="api" style="text-align:left" name="<?=$api->id;?>" id="<?=$api->displayName?>" filter="<?=$api->id." ".$api->endpoint." ".$api->displayName?>">
                                        <div class="ellipsis pull-left" style="width:45%"><strong><?=$api->displayName?></strong></div>
                                        <div class="ellipsis" style="padding-left: 5px;width:49%"><i>/<?=$api->endpoint?></i></div></a>
                                    <? endforeach ?>
                                    <?}else{?>
                                    <p id='selectedApiPlaceholder' class="depth"><?=$this->translate("Selected Apis")?></p>
                                    <?}?>
                                </div>
                            </div>
                            <div class="clearfix" id="clearApi">
                                <? if(!empty($selectedAPI)){ foreach($selectedAPI as $api):?>
                                <input type="hidden" class="<?=$api->displayName?>" id="<?=$api->id?>" name="selected_api[]" value="<?=$api->id?>">
                                <? endforeach ?><?}?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="control-group">
                <label class="control-label"><? echo $this->translate("Auths")?></label>
                <div class="controls btn-group-vertical" style="margin-left: 20px">
                    <div class="well second-level well-small pull-left">
                        <input type="text" filterType="Auth" class="filter-field filterMe" id="filterAuth" style="margin-bottom: 10px" rel="tooltip" title="<?//=$idTip?>" value="" placeholder="<?=$this->translate("Filter Auths by...")?>" />
                        <div id="auth-group">
                            <div class="btn-group btn-group-vertical pull-left" id="selectAuth">
                                <? foreach($this->auths as $auth){
                                    $policyAuthIds = $policy->getAuthIds();
                                    switch ($auth->type){
                                        case "basic":
                                            $string = $auth->basicAuth->username . "/" . $auth->basicAuth->password;
                                            $color = "label label-info";
                                            break;
                                        case "wsse":
                                            $string = $auth->wsseAuth->username . "/" . $auth->wsseAuth->password;
                                            $color = "label label-success";
                                            break;
                                        case "authKey":
                                            $string = $auth->authKeyAuth->keyValue;
                                            $color = "label label-important";
                                            break;
                                        case "ipWhiteList":
                                            $i=0;
                                            $string = "";
                                            $color = "label label-warning";
                                            foreach($auth->ipWhiteListAuth->ips as $ip){
                                                $string += ($i > 0) ? ", " . $ip : $ip;
                                                $i++;
                                            }
                                            break;
                                    }
                                    if (!empty($policyAuthIds)) {
                                        $a = 0;
                                        foreach ($policyAuthIds[0]->authIds as $policyAuthId) {
                                            if ($policyAuthId === $auth->id) { $selectedAuth[] = array("auth" => $auth, "string" => $string, "color" => $color); $a = 1; break; }
                                        }
                                        if ($a == 1)continue; //if the auth is already selected, we don't want it to appear in the selectable list
                                    }?>
                                <a class="btn moveSelected filterAuth" rel="tooltip" data-placement="left" title="<?=$auth->type . " " . $auth->id . " " . $string?>" type="auth" style="text-align:left" id="<?=$auth->id?>"
                                   name="<?=$string?>" filter="<?=$auth->id . " " . $string . " " . $auth->type?>">
                                    <div class="ellipsis pull-left auth-type"><strong class="<?=$color?>"><?=$auth->type?></strong></div>
                                    <div class="ellipsis" style="padding-left: 5px;width:65%"><?=$string?></div></a>
                                <? } ?>
                            </div>
                            <div class="btn-group btn-group-vertical pull-right">
                                <div class="well well-small third-level" style="min-height: 180px; margin-bottom:0" id="selectedAuth">
                                    <? if(!empty($selectedAuth)){foreach($selectedAuth as $item): ?>
                                    <? $string = $item['string']; $auth = $item['auth']; $color = $item['color'];?>
                                    <a class="btn moveSelected filterAuth" rel="tooltip" data-placement="left" title="<?=$auth->type . " " . $auth->id . " " . $string?>" type="auth" style="text-align:left" id="<?=$auth->id?>"
                                       name="<?=$string?>" filter="<?=$auth->id . " " . $string . " " . $auth->type?>">
                                        <div class="ellipsis pull-left auth-type"><strong class="<?=$color?>"><?=$auth->type?></strong></div>
                                        <div class="ellipsis" style="padding-left: 5px;width:65%"><?=$string?></div></a>
                                    <? endforeach ?>
                                    <?}else{?>
                                    <p id='selectedAuthPlaceholder' class="depth"><?=$this->translate("Selected Auths")?></p>
                                    <?}?>
                                </div>
                            </div>
                            <div class="clearfix" id="clearAuth">
                                <? if(!empty($selectedAuth)){foreach($selectedAuth as $item): ?>
                                <? $string = $item['string']; $auth = $item['auth'];?>
                                <input type="hidden" class="<?=$auth->id?>" id="<?=$string?>" name="selected_auth[]" value="<?=$auth->id?>">
                                <? endforeach ?><?}?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?
            $per_second_counter = $context->getRateLimitPerSecond();
            $per_second_warning = !empty($per_second_counter) ? $per_second_counter->getWarning() : null;
            $per_second_threshold = !empty($per_second_counter) ? $per_second_counter->getThreshold() : null;
            $per_minute_counter = $context->getRateLimitPerMinute();
            $per_minute_warning = !empty($per_minute_counter) ? $per_minute_counter->getWarning() : null;
            $per_minute_threshold = !empty($per_minute_counter) ? $per_minute_counter->getThreshold() : null;
            $per_day_counter = $context->getQuotaPerDay();
            $per_day_warning = !empty($per_day_counter) ? $per_day_counter->getWarning() : null;
            $per_day_threshold = !empty($per_day_counter) ? $per_day_counter->getThreshold() : null;
            $per_week_counter = $context->getQuotaPerWeek();
            $per_week_warning = !empty($per_week_counter) ? $per_week_counter->getWarning() : null;
            $per_week_threshold = !empty($per_week_counter) ? $per_week_counter->getThreshold() : null;
            $per_month_counter = $context->getQuotaPerMonth();
            $per_month_warning = !empty($per_month_counter) ? $per_month_counter->getWarning() : null;
            $per_month_threshold = !empty($per_month_counter) ? $per_month_counter->getThreshold() : null;
            $advancedOpen = (!empty($per_second_warning) || !empty($per_second_threshold)
                || !empty($per_minute_warning) || !empty($per_minute_threshold)
                || !empty($per_day_warning) || !empty($per_day_threshold)
                || !empty($per_week_warning) || !empty($per_week_threshold)
                || !empty($per_month_warning) || !empty($per_month_threshold)
                || !empty($policy->headerTransformations) || !empty($policy->properties)
                || !empty($policy->tdr->dynamicTdrs)
                || !empty($policy->tdrData->staticTdrs));?>
            <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 second-level well-small" style="<?= $advancedOpen?"":"display:none"?>">
                <div id="quotaGroup">
                    <div class="control-group <?=(!empty($validationErrors['per_second']))?"error":""?>" id="secondQuotaGroup">
                        <label class="control-label" for="TPS"><? echo $this->translate("TPS")?></label>
                        <div class="controls">
                            <select class="input-small" name="per_second[action]" rel="tooltip" title="<?=$rateActionTip?>">
                                <?php $action = !empty($per_second_counter) ? $per_second_counter->getAction() : null; ?>
                                <option value="<?php echo Action::$IGNORE ?>"<?php if ($action === Action::$IGNORE) {echo ' selected="selected"';} ?>><? echo $this->translate("Ignore")?></option>
                                <option value="<?php echo Action::$REJECT ?>"<?php if ($action === Action::$REJECT) {echo ' selected="selected"';} ?>><? echo $this->translate("Reject")?></option>
                            </select>
                            <input type="text" class="input-small" id="TPS" name="per_second[warning]"
                                   rel="tooltip" title="<?=$rateWarningTip?>"
                                   placeholder="<? echo $this->translate("Warning")?>" <?php if (!empty($per_second_warning)) { echo 'value="'.$per_second_warning.'"';} ?>>
                            <input type="text" class="input-small" name="per_second[threshold]"
                                   rel="tooltip" title="<?=$rateThresholdTip?>"
                                   placeholder="<? echo $this->translate("Threshold")?>" <?php if (!empty($per_second_threshold)) { echo 'value="'.$per_second_threshold.'"';} ?>>
                            <span class="help-inline"><?=@$validationErrors['per_second']?></span>
                        </div>
                    </div>
                    <div class="control-group <?=(!empty($validationErrors['per_minute']))?"error":""?>" id="minuteQuotaGroup">
                        <label class="control-label" for="TPM"><? echo $this->translate("TPM")?></label>
                        <div class="controls">
                            <select class="input-small" name="per_minute[action]" rel="tooltip" title="<?=$rateActionTip?>">
                                <?php $action = !empty($per_minute_counter) ? $per_minute_counter->getAction() : null; ?>
                                <option value="<?php echo Action::$IGNORE ?>"<?php if ($action === Action::$IGNORE) {echo ' selected="selected"';} ?>><? echo $this->translate("Ignore")?></option>
                                <option value="<?php echo Action::$REJECT ?>"<?php if ($action === Action::$REJECT) {echo ' selected="selected"';} ?>><? echo $this->translate("Reject")?></option>
                            </select>
                            <input type="text" class="input-small" id="TPM" name="per_minute[warning]"
                                   rel="tooltip" title="<?=$rateWarningTip?>"
                                   placeholder="<? echo $this->translate("Warning")?>" <?php if (!empty($per_minute_warning)) { echo 'value="'.$per_minute_warning.'"';} ?>>
                            <input type="text" class="input-small" name="per_minute[threshold]"
                                   rel="tooltip" title="<?=$rateThresholdTip?>"
                                   placeholder="<? echo $this->translate("Threshold")?>" <?php if (!empty($per_minute_threshold)) { echo 'value="'.$per_minute_threshold.'"';} ?>>
                            <span class="help-inline"><?=@$validationErrors['per_minute']?></span>
                        </div>
                    </div>
                    <div class="control-group <?=(!empty($validationErrors['per_day']))?"error":""?>" id="dailyQuotaGroup">
                        <label class="control-label" for="daily"><? echo $this->translate("Daily")?></label>
                        <div class="controls">
                            <select class="input-small" name="per_day[action]" rel="tooltip" title="<?=$rateActionTip?>">
                                <?php $action = !empty($per_day_counter) ? $per_day_counter->getAction() : null; ?>
                                <option value="<?php echo Action::$IGNORE ?>"<?php if ($action === Action::$IGNORE) {echo ' selected="selected"';} ?>><? echo $this->translate("Ignore")?></option>
                                <option value="<?php echo Action::$REJECT ?>"<?php if ($action === Action::$REJECT) {echo ' selected="selected"';} ?>><? echo $this->translate("Reject")?></option>
                            </select>
                            <input type="text" class="input-small" id="daily" name="per_day[warning]"
                                   rel="tooltip" title="<?=$rateWarningTip?>"
                                   placeholder="<? echo $this->translate("Warning")?>" <?php if (!empty($per_day_warning)) { echo 'value="'.$per_day_warning.'"';} ?>>
                            <input type="text" class="input-small" name="per_day[threshold]"
                                   rel="tooltip" title="<?=$rateThresholdTip?>"
                                   placeholder="<? echo $this->translate("Threshold")?>" <?php if (!empty($per_day_threshold)) { echo 'value="'.$per_day_threshold.'"';} ?>>
                            <span class="help-inline"><?=@$validationErrors['per_day']?></span>
                        </div>
                    </div>
                    <div class="control-group <?=(!empty($validationErrors['per_week']))?"error":""?>" id="weeklyQuotaGroup">
                        <label class="control-label" for="TPW"><? echo $this->translate("Weekly")?></label>
                        <div class="controls">
                            <select class="input-small" name="per_week[action]" rel="tooltip" title="<?=$rateActionTip?>">
                                <?php $action = !empty($per_week_counter) ? $per_week_counter->getAction() : null; ?>
                                <option value="<?php echo Action::$IGNORE ?>"<?php if ($action === Action::$IGNORE) {echo ' selected="selected"';} ?>><? echo $this->translate("Ignore")?></option>
                                <option value="<?php echo Action::$REJECT ?>"<?php if ($action === Action::$REJECT) {echo ' selected="selected"';} ?>><? echo $this->translate("Reject")?></option>
                            </select>
                            <input type="text" class="input-small" id="TPW" name="per_week[warning]"
                                   rel="tooltip" title="<?=$rateWarningTip?>"
                                   placeholder="<? echo $this->translate("Warning")?>" <?php if (!empty($per_week_warning)) { echo 'value="'.$per_week_warning.'"';} ?>>
                            <input type="text" class="input-small" name="per_week[threshold]"
                                   rel="tooltip" title="<?=$rateThresholdTip?>"
                                   placeholder="<? echo $this->translate("Threshold")?>" <?php if (!empty($per_week_threshold)) { echo 'value="'.$per_week_threshold.'"';} ?>>
                            <span class="help-inline"><?=@$validationErrors['per_week']?></span>
                        </div>
                    </div>
                    <div class="control-group <?=(!empty($validationErrors['per_month']))?"error":""?>" id="monthlyQuotaGroup">
                        <label class="control-label" for="monthly"><? echo $this->translate("Monthly")?></label>
                        <div class="controls">
                            <select class="input-small" name="per_month[action]" rel="tooltip" title="<?=$rateActionTip?>">
                                <?php $action = !empty($per_month_counter) ? $per_month_counter->getAction() : null; ?>
                                <option value="<?php echo Action::$IGNORE ?>"<?php if ($action === Action::$IGNORE) {echo ' selected="selected"';} ?>><? echo $this->translate("Ignore")?></option>
                                <option value="<?php echo Action::$REJECT ?>"<?php if ($action === Action::$REJECT) {echo ' selected="selected"';} ?>><? echo $this->translate("Reject")?></option>
                            </select>
                            <input type="text" class="input-small" id="monthly" name="per_month[warning]"
                                   rel="tooltip" title="<?=$rateWarningTip?>"
                                   placeholder="<? echo $this->translate("Warning")?>" <?php if (!empty($per_month_warning)) { echo 'value="'.$per_month_warning.'"';} ?>>
                            <input type="text" class="input-small" name="per_month[threshold]"
                                   rel="tooltip" title="<?=$rateThresholdTip?>"
                                   placeholder="<? echo $this->translate("Threshold")?>" <?php if (!empty($per_month_threshold)) { echo 'value="'.$per_month_threshold.'"';} ?>>
                            <span class="help-inline"><?=@$validationErrors['per_month']?></span>
                        </div>
                    </div>
                </div>
                <div id="propertyGroup">
                <? SharedViewUtility::includePropertiesSnippet($policy->properties, $validationErrors); ?>
                </div>
                <div id="headerTransGroup">
                <? SharedViewUtility::includeHeaderTransformationsSnippet($policy->headerTransformations, $validationErrors); ?>
                </div>
                <div id="tdrRuleGroup">
                <? SharedViewUtility::includeTdrRulesSnippet($policy->tdr, $validationErrors); ?>
                </div>
                <div class="hidden" id="relatedPropertiesTree"><?
                    print htmlentities($relatedProperties);
                ?></div>
            </div>
            <input type="hidden" name="_faction" value="submit" />
            <input type="hidden" name="_fid" value="<?php echo $flow->id; ?>" />
            <input type="submit" class="btn" rel="tooltip" title="<?=$submitButtonTip?>" data-placement="right" />
        </fieldset>
    </form>
</div> <!-- /container -->
