<%@include file="include/header.jsp"%>
<%!
//-----------------------------------------------
boolean checkParam(DhcpSetupData data){
	if (!isValidIp(data.listenIp)) {
		errList.add(translate("Invalid listen IP."));
		return false;
	}

	if (!isValidIp(data.serverIdentifier)) {
		errList.add(translate("Invalid server identifier."));
		return false;
	}

	if (!isValidIp(data.startIp)) {
		errList.add(translate("Invalid start IP."));
		return false;
	}

	if (!isValidIp(data.endIp)) {
		errList.add(translate("Invalid end IP."));
		return false;
	}

	if (!isValidIp(data.subnetMask)) {
		errList.add(translate("Invalid subnet mask."));
		return false;
	}

	if (!isValidIp(data.gatewayIp)) {
		errList.add(translate("Invalid gateway IP."));
		return false;
	}

	if (isNotEmpty(data.tftpServer) && !isValidIp(data.tftpServer)) {
		errList.add(translate("Invalid TFTP server IP."));
		return false;
	}

	// Backup server.
	if(isNotEmpty(data.bsListenIp)
		|| isNotEmpty(data.bsServerIdentifier)
		|| isNotEmpty(data.bsStartIp)
		|| isNotEmpty(data.bsEndIp)){
	
		if(isEmpty(data.bsListenIp)
			|| isEmpty(data.bsServerIdentifier)
			|| isEmpty(data.bsStartIp)
			|| isEmpty(data.bsEndIp)){
		
			if (!isValidIp(data.bsListenIp)) {
				errList.add(translate("Invalid backup server listen IP."));
				return false;
			}
		
			if (!isValidIp(data.bsServerIdentifier)) {
				errList.add(translate("Invalid backup server identifier."));
				return false;
			}

			if (!isValidIp(data.bsStartIp)) {
				errList.add(translate("Invalid backup server start IP."));
				return false;
			}

			if (!isValidIp(data.bsEndIp)) {
				errList.add(translate("Invalid backup server end IP."));
				return false;
			}
		}
	}

	if(DhcpSetupDao.isOverlappedIpRange(data.startIp, data.endIp, data.bsStartIp, data.bsEndIp)){
		errList.add(translate("Backup DHCP IP range must not overlap with the primary IP range."));
		return false;
	}

	return true;
}

//-----------------------------------------------
void stopOrRestart(DhcpSetupDao dao, boolean runDhcp){
	if(!runDhcp){
		dao.stopServer();
	}
	else{
		dao.restartServer();
	}

	// sleep for 2 seconds
	try{
		Thread.sleep(2000); // 2000 milliseconds = 2 seconds
	}catch(Exception e){}

	if(!runDhcp){
		if(!dao.isStarted()){
			succList.add(translate("DHCP server has been stopped."));
		}
		else{
			warnList.add(translate("Attempted to stop the DHCP server, but could not confirm if it succeeded."));
		}
	}
	else{
		if(dao.isStarted()){
			succList.add(translate("DHCP server has been started."));
		}
		else{
			warnList.add(translate("Attempted to start the DHCP server, but could not confirm if it succeeded."));
		}
	}
}

//-----------------------------------------------
void update(DhcpSetupDao dao){
	if(demoFlag){
		errList.add("Not allowed on demo site.");
		return;
	}

	// New data.
	DhcpSetupData data = new DhcpSetupData();
	data.listenIp = paramString("listenIp");
	data.serverIdentifier = paramString("serverIdentifier");
	data.startIp = paramString("startIp");
	data.endIp = paramString("endIp");
	data.subnetMask = paramString("subnetMask");
	data.gatewayIp = paramString("gatewayIp");
	data.dnsIp = paramString("dnsIp");
	data.defaultDomain = paramString("defaultDomain");
	data.leaseSeconds = paramInt("leaseSeconds");
	data.ntpIp = paramString("ntpIp");
	data.tftpServer = paramString("tftpServer");
	data.bootFile = paramString("bootFile");
	data.wpadUrl = paramString("wpadUrl");
	data.maxPoolSize = paramInt("maxPoolSize");
	data.runDhcp = paramBoolean("runDhcp");
	data.preventConflict = paramBoolean("preventConflict");

	// Backup server.
	data.bsListenIp = paramString("bsListenIp");
	data.bsServerIdentifier = paramString("bsServerIdentifier");
	data.bsStartIp = paramString("bsStartIp");
	data.bsEndIp = paramString("bsEndIp");

	if(new ClusterDao().isMaster() && data.preventConflict){
		warnList.add(translate("Prevent Conflict option can't be selected when clustering is enabled."));
	}

	// See if we need to restart it.
	// And if we need to stop it as well.
	boolean restartFlag = dao.needToRestart(data);

	// Validate and update it.
	if(checkParam(data) && dao.update(data)){
		//succList.add(translate("Update finished."));

		if(restartFlag){
			stopOrRestart(dao, data.runDhcp);
		}
		else{
			succList.add(translate("Settings have been reloaded."));
		}
	}
}
%>
<%
//-----------------------------------------------
// Set permission for this page.
permission.addAdmin();
permission.addSubAdmin();

//Check permission.
if(!checkPermission()){
	return;
}

// Create data access object.
DhcpSetupDao dao = new DhcpSetupDao();

// Action.
String actionFlag = paramString("actionFlag");
if(actionFlag.equals("update")){
	update(dao);
}

// Global.
DhcpSetupData data = dao.selectOne();

// Active tab.
String tabActive0 = "";
String tabActive1 = "";
String tabActive2 = "";

String showActive0 = "";
String showActive1 = "";
String showActive2 = "";

int tabIdx = paramInt("tabIdx");
if(tabIdx == 0){
	tabActive0 = " active";
	showActive0 = " show active";
}
else if(tabIdx == 1){
	tabActive1 = " active";
	showActive1 = " show active";
}
else if(tabIdx == 2){
	tabActive2 = " active";
	showActive2 = " show active";
}
%>
<!-- Action info -->
<%@include file="include/ab-notify.jsp"%>
<!-- /Action info -->

<!-- Breadcrumb -->
<div class="container-fluid primary" style="margin-top:-5px;">
	<ol class="breadcrumb" style="margin-left:10px; margin-right:10px;">
		<li class="breadcrumb-item"><%= translate("DHCP")%></li>
		<li class="breadcrumb-item text-info"><%= translate("SETUP")%></li>
	</ol>
</div>
<!-- /Breadcrumb -->

<!-- Main content -->
<div class="container-fluid">

	<!-- Tab -->
	<div>
		<ul class="nav nav-tabs" style="margin-left:10px; margin-right:10px;">
			<li class="nav-item" onclick="javascript:$('#tabIdx').val(0);">
				<a class="nav-link<%= tabActive0%>" data-toggle="tab" href="#tab0"><%= translate("BASIC SETUP")%></a>
			</li>
			<li class="nav-item" onclick="javascript:$('#tabIdx').val(1);">
				<a class="nav-link<%= tabActive1%>" data-toggle="tab" href="#tab1"><%= translate("ADVANCED")%></a>
			</li>
			<li class="nav-item" onclick="javascript:$('#tabIdx').val(2);">
				<a class="nav-link<%= tabActive2%>" data-toggle="tab" href="#tab2"><%= translate("BACKUP SERVER")%></a>
			</li>
		</ul>
	</div>
	<!-- Tab -->

	<!-- Form -->
	<form action="<%= getPageName()%>" method="post">
		<input type="hidden" name="actionFlag" value="update">
		<input type="hidden" id="tabIdx" name="tabIdx" value="<%= tabIdx%>">

		<!-- Tab content -->
		<div id="myTabContent" class="tab-content">

			<!-- Basic -->
			<div class="tab-pane <%= showActive0%>" id="tab0">
				<div class="card bg-light m-2 expand-lg">
					<div class="card-body">
						<fieldset>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Listen IP")%></label>
								<input type="text" class="form-control" id="listenIp" name="listenIp"
									value="<%= data.listenIp%>">
								<small id="input-help" class="form-text text-muted">
									<%= translate("Restart is required after changing Listen IP.")%>
								</small>
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Server Identifier")%></label>
								<input type="text" class="form-control" id="serverIdentifier" name="serverIdentifier"
									value="<%= data.serverIdentifier%>">
								<small id="input-help" class="form-text text-muted">
									<%= translate("The actual IP address of the network interface.")%>
								</small>
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Start IP")%></label>
								<input type="text" class="form-control" id="startIp" name="startIp"
									value="<%= data.startIp%>">
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("End IP")%></label>
								<input type="text" class="form-control" id="endIp" name="endIp"
									value="<%= data.endIp%>">
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Subnet Mask")%></label>
								<input type="text" class="form-control" id="subnetMask" name="subnetMask"
									value="<%= data.subnetMask%>">
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Gateway IP")%></label>
								<input type="text" class="form-control" id="gatewayIp" name="gatewayIp"
									value="<%= data.gatewayIp%>">
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("DNS IP")%></label>
								<input type="text" class="form-control" id="dnsIp" name="dnsIp"
									value="<%= data.dnsIp%>">
								<small id="input-help" class="form-text text-muted">
									<%= translate("Multiple IP addresses must be separated by commas.")%>
								</small>
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Lease Seconds")%></label>
								<input type="text" class="form-control" id="leaseSeconds" name="leaseSeconds"
									value="<%= data.leaseSeconds%>">
							</div>
							<div class="form-group col-lg-8">
								<div class="custom-control custom-checkbox">
									<input type="checkbox" class="custom-control-input" id="runDhcp"
										name="runDhcp" <%if(data.runDhcp){out.print("checked");}%>>
									<label for="runDhcp" class="custom-control-label"><%= translate("Run DHCP")%></label>
								</div>
							</div>
							<div class="form-group col-lg-8">
								<button type="submit" class="btn btn-primary"><%= translate("SUBMIT")%></button>
							</div>
						</fieldset>
					</div>
				</div>
			</div>
			<!-- /Basic -->

			<!-- Advanced -->
			<div class="tab-pane fade<%= showActive1%>" id="tab1">
				<div class="card bg-light m-2 expand-lg">
					<div class="card-body">
						<fieldset>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Default Domain")%></label>
								<input type="text" class="form-control" id="defaultDomain" name="defaultDomain"
									value="<%= data.defaultDomain%>">
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("NTP IP")%></label>
								<input type="text" class="form-control" id="ntpIp" name="ntpIp"
									value="<%= data.ntpIp%>">
								<small id="input-help" class="form-text text-muted">
									<%= translate("Multiple IP addresses must be separated by commas.")%>
								</small>
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("TFTP SERVER")%></label>
								<input type="text" class="form-control" id="tftpServer" name="tftpServer"
									value="<%= data.tftpServer%>">
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("BOOT FILE")%></label>
								<input type="text" class="form-control" id="bootFile" name="bootFile"
									value="<%= data.bootFile%>">
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("WPAD URL")%></label>
								<input type="text" class="form-control" id="wpadUrl" name="wpadUrl"
									value="<%= data.wpadUrl%>">
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label">
									<%= translate("Maximum Pool Size")%>
									&nbsp;<i class="fa fa-question-circle south-east"
										title="<%= translate("Maximum number of IPs in the pool. This affects how many IPs will be pre-initialized. Default is 20000.")%>"></i>
								</label>
								<div class="input-group">
									<input type="text" class="form-control" id="maxPoolSize" name="maxPoolSize"
										value="<%= data.maxPoolSize%>">
									<div class="input-group-append">
										<span class="input-group-text">255 ~ 200,000</span>
									</div>
								</div>
							</div>
							<div class="form-group col-lg-8">
								<div class="custom-control custom-checkbox">
									<input type="checkbox" class="custom-control-input" id="preventConflict"
										name="preventConflict" <%if(data.preventConflict){out.print("checked");}%>>
									<label class="custom-control-label" for="preventConflict">
										<%= translate("Prevent Conflict")%>
										&nbsp;<i class="fa fa-question-circle south-east"
												title="<%= translate("When another DHCP server is active in the network, we yield to avoid conflict.")%>"></i>
									</label>
								</div>
							</div>
							<div class="form-group col-lg-8">
								<button type="submit" class="btn btn-primary"><%= translate("SUBMIT")%></button>
							</div>
						</fieldset>
					</div>
				</div>
			</div>
			<!-- /Advanced -->

			<!-- Backup Server -->
			<div class="tab-pane <%= showActive2%>" id="tab2">
				<div class="card bg-light m-2 expand-lg">
					<div class="card-body">
						<fieldset>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Listen IP")%></label>
								<input type="text" class="form-control" id="bsListenIp" name="bsListenIp"
									value="<%= data.bsListenIp%>">
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Server Identifier")%></label>
								<input type="text" class="form-control" id="bsServerIdentifier" name="bsServerIdentifier"
									value="<%= data.bsServerIdentifier%>">
								<small id="input-help4" class="form-text text-muted">
									<%= translate("Must be one of the IP addresses of the slave nodes.")%>
								</small>
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("Start IP")%></label>
								<input type="text" class="form-control" id="bsStartIp" name="bsStartIp"
									value="<%= data.bsStartIp%>">
								<small id="input-help5" class="form-text text-muted">
									<%= translate("Must not overlap with the primary IP range.")%>
								</small>
							</div>
							<div class="form-group col-lg-8">
								<label class="col-form-label"><%= translate("End IP")%></label>
								<input type="text" class="form-control" id="bsEndIp" name="bsEndIp"
									value="<%= data.bsEndIp%>">
							</div>
							<div class="form-group col-lg-8">
								<button type="submit" class="btn btn-primary"><%= translate("SUBMIT")%></button>
							</div>
						</fieldset>
					</div>
				</div>
			</div>
			<!-- /Backup Server -->

		</div>
		<!-- Tab content -->

	</form>
	<!-- /Form -->

</div>
<!-- /Main content -->

<%@include file="include/footer.jsp"%>

<script>
//-----------------------------------------------
// Restricts input for each element in the set of matched elements to the given inputFilter.
(function($) {
	$.fn.inputFilter = function(inputFilter){
		return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function(){
			if (inputFilter(this.value)){
				this.oldValue = this.value;
				this.oldSelectionStart = this.selectionStart;
				this.oldSelectionEnd = this.selectionEnd;
			} else if (this.hasOwnProperty("oldValue")){
				this.value = this.oldValue;
				this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
			} else {
				this.value = "";
			}
		});
	};
}(jQuery));

// Install input filters.
$("#listenIp").inputFilter(function(value){
	if(value == ""){
		return true;
	}

	return /^[\d\.:]*$/.test(value);
});
$("#startIp").inputFilter(function(value){
	if(value == ""){
		return true;
	}

	return /^[\d\.:]*$/.test(value);
});
$("#endIp").inputFilter(function(value){
	if(value == ""){
		return true;
	}

	return /^[\d\.:]*$/.test(value);
});
$("#subnetMask").inputFilter(function(value){
	if(value == ""){
		return true;
	}

	return /^[\d\.:]*$/.test(value);
});
$("#gatewayIp").inputFilter(function(value){
	if(value == ""){
		return true;
	}

	return /^[\d\.:]*$/.test(value);
});
$("#dnsIp").inputFilter(function(value){
	if(value == ""){
		return true;
	}

	return /^[\d\.,]*$/.test(value);
});
$("#ntpIp").inputFilter(function(value){
	if(value == ""){
		return true;
	}

	return /^[\d\.,]*$/.test(value);
});
$("#tftpServer").inputFilter(function(value){
	if(value == ""){
		return true;
	}

	return /^[\d\.:]*$/.test(value);
});
</script>
