<%- include('top') %>
<script type="text/javascript">
	// Require login to see this page.
	app.auth.forceLogin();
</script>

<style type="text/css">
	label.form-label{
		font-weight: bold;
		margin-bottom: 1px;
	}

	.card-title{
		font-weight: bold;
	}

	div.form-group{
		margin-bottom: 1em;
	}

	select {
		font-family: "system-ui", "FontAwesome";
	}

</style>

<script type="text/javascript">

	function providerGet(){
		app.api.options('dns', function(error, res){
			for(let provider of res.results){
				$.scope.providerSelect.push(provider);

				for(let field in provider.fields){
					$.scope.providerField.push({
						...provider.fields[field],
						keyName: field,
						provider: provider.name
					});
				}
			}
		});
	}

	function providerShowForm(){
		let $el = $(event.target);
		$('.jq-repeat-providerField').each(function(){
			let $el = $(this)
			$el.hide()
			$el.find('input').prop('disabled', true)
		});

		$(`.provider-form-${$el.val()}`).each(function(){
			let $el = $(this)
			$el.show()
			$el.find('input').prop("disabled",false)
		});
	}

	$.scope.DnsProvider.parseData = function(row){
		row['created_on_text'] = moment(row['updated_on'], "x").fromNow();
		row['domainsString'] = JSON.stringify(row.domains);
		return row
	};

	async function ddnsLoadCurrentIp(){
		try{
			let res = await app.api.get('dns/dynamic/ip');
			$('#ddns-current-ip').text(res.ip);
		}catch(error){
			$('#ddns-current-ip').text('unavailable');
		}
	}

	$(document).ready(async function(){
		// Set the jq Templates
		$.scope.providerField.put = function(){};
		$.scope.DnsProvider.push(...(await app.api.get('dns?detail=true')).results);

		// Dynamic DNS: existing records, the domain dropdown, and the current IP.
		$.scope.DynamicRecord.push(...(await app.api.get('dns/dynamic')).results);
		$.scope.ddnsDomain.push(...(await app.api.get('dns/domain?detail=true')).results);
		ddnsLoadCurrentIp();

		// Populate
		providerGet();

		app.subscribe(/^model:/, function(data, topic){
			let [group, Model, action, pk] = topic.split(':');
			console.log('WS:', group, Model, action, pk, data);
		});

		app.subscribe(/^model:.+:create/, function(data, topic){
			try{
				let [group, Model, action, pk] = topic.split(':');
				$.scope[Model].unshift(data)
			}catch{}
		});

		app.subscribe(/^model:.+:remove/, function(data, topic){
			try{
				let [group, Model, action, pk] = topic.split(':');
				$.scope[Model].remove(pk);
			}catch{}
		});

		app.subscribe(/^model:.+:update/, function(data, topic){
			try{
				let [group, Model, action, pk] = topic.split(':');
				$.scope[Model].update(pk, data)
			}catch{}
		});
	});

</script>
<div class="container mt-4">
<div class="row mb-3" style="display:none">
	<div class="col-md-3">
		<div class="card shadow-lg mb-3">

			<div class="card-header text-center">
				<span class="card-icon float-start">
					<i class="fa-solid fa-user-plus"></i>
				</span>
				<span class="card-title">
					Add DNS Provider
				</span>
				<span class="float-end">
					<a href="/docs/dns" class="text-reset me-2" title="Help"><i class="fa-solid fa-circle-question"></i></a>
					<i class="fa-solid fa-circle-minus"></i>
				</span>
			</div>

			<div class="card-header actionMessage" style="display:none"></div>
			<div class="card-body d-none d-md-block">
				<form action="dns/" onsubmit="formAJAX(this)">
					<div class="form-group">
						<label for="name" class="form-label">
							Name
						</label>
						<input type="text"  name="name" class="form-control" placeholder="ex: production" validate=":3"/>
						<b class="invalid-feedback"></b>
					</div>

					<div class="form-group">
						<label for="dnsProvider" class="form-label">
							DNS provider
						</label>
						<select name="dnsProvider" class="form-select" aria-label="Default select example" validate=":1" oninput="providerShowForm()">
							<option value="" selected>Select a provider</option>
							<option jq-repeat="providerSelect" value="{{name}}">{{{displayIconUni}}} {{name}}</option>

						</select>
						<b class="invalid-feedback"></b>
					</div>

					<div class="form-group provider-form-{{ provider }}" jq-repeat="providerField" style="display:none;">
						<label for="{{ keyName }}" class="form-label">
							{{displayName}}
						</label>
						<input type="text"  name="{{ keyName }}" class="form-control" validate=":3" disabled/>
						<b class="invalid-feedback"></b>
					</div>

					<hr />
					<button type="submit" class="btn btn-success">
						<i class="fa-solid fa-plus"></i>
						Add
					</button>
				</form>
			</div>
		</div>
	</div>
	<div class="col-md-9">
		<div class="row row-cols-1 row-cols-md-2 g-4">
			
			<div jq-repeat="DnsProvider" jq-repeat-index="id" style="display:none" class="col">
				<div class="card shadow-lg">

					<div class="card-header text-center">
						<span class="card-icon float-start">
							<i class="fa-solid fa-record-vinyl"></i>
						</span>
						<span class="card-title">
							 {{ dnsProvider }} DNS
						</span>
						<span class="float-end">
							<i class="fa-solid fa-circle-minus"></i>
						</span>
					</div>

					<div class="card-header actionMessage" style="display:none"></div>
					<div class="card-body">
						<div class="row">
								<h3><img height="32px" src="{{ displayIconHtml }}"/> {{name}} </h3>
						</div>
						<div>
							{{#domains}}
							<b class="me-2 my-1 badge text-bg-info rounded-pill fs-6">
								{{domain}}
							</b>
							{{/domains}}
						</div>
					</div>
					<div class="card-footer">
						Added <b class="momentFromNow" data-date="{{ updated_on }}">{{ created_on_text }}</b> by <b>{{ created_by }}</b>
						<span class="float-end text-end">
							<button type="button" class="btn btn-warning" method="POST" action="dns/domain/refresh/{{id}}" onclick="formAJAX()">
								<i class="fa-solid fa-rotate"></i>
							</button>
							<button type="button" class="btn btn-danger" method="DELETE" action="dns/{{id}}" onclick="formAJAX()">
								<i class="fa-solid fa-trash-can"></i>
							</button>
						</span>
					</div>

					
				</div>

			</div>
		</div>

	</div>
</div>
<div class="row mb-3">
	<div class="col-12">
		<div class="card shadow-lg">
			<div class="card-header d-flex align-items-center">
				<span class="card-icon me-2"><i class="fa-solid fa-tower-broadcast"></i></span>
				<span class="card-title">Dynamic A Records</span>
				<a href="/docs/dns" class="text-reset ms-2" title="Help"><i class="fa-solid fa-circle-question"></i></a>
				<span class="ms-auto text-muted small">
					This server's public IP:
					<span class="badge text-bg-primary fs-6"><i class="fa-solid fa-globe me-1"></i><span id="ddns-current-ip">…</span></span>
				</span>
			</div>
			<div class="card-header actionMessage" style="display:none"></div>

			<div class="card-body">
				<p class="text-muted mb-3">
					These A records are pointed at this server's public IP automatically —
					every 4 hours and immediately when added. Enter <code>@</code> as the host
					for the domain apex.
				</p>

				<!-- Add form -->
				<form action="dns/dynamic" onsubmit="formAJAX(this)" class="row g-2 align-items-end mb-4">
					<div class="col-12 col-md-5">
						<label class="form-label">Domain</label>
						<select name="domain" class="form-select" validate=":1">
							<option value="" selected>Select a domain…</option>
							<option jq-repeat="ddnsDomain" value="{{domain}}">{{domain}}</option>
						</select>
					</div>
					<div class="col-8 col-md-5">
						<label class="form-label">Host</label>
						<input type="text" name="name" class="form-control" placeholder="home   ·   @ for apex" validate=":1" />
						<b class="invalid-feedback"></b>
					</div>
					<div class="col-4 col-md-2 d-grid">
						<button type="submit" class="btn btn-success"><i class="fa-solid fa-plus me-1"></i>Add</button>
					</div>
				</form>

				<!-- Record list -->
				<div class="list-group">
					<div jq-repeat="DynamicRecord" jq-repeat-index="id"
						class="list-group-item d-flex align-items-center flex-wrap gap-2">

						<div class="me-auto">
							<div class="fw-bold fs-5">
								<i class="fa-solid fa-circle-nodes text-secondary me-1"></i>{{ fqdn }}
							</div>
							<div class="small text-muted">
								{{#last_ip}}
									<i class="fa-solid fa-arrow-right-long"></i>
									<span class="badge text-bg-success">{{ last_ip }}</span>
									updated <span class="momentFromNow" data-date="{{ last_updated }}">recently</span>
								{{/last_ip}}
								{{^last_ip}}
									<span class="badge text-bg-secondary">awaiting first update…</span>
								{{/last_ip}}
								{{#last_status}}
									<span class="text-danger ms-2"><i class="fa-solid fa-triangle-exclamation me-1"></i>{{ last_status }}</span>
								{{/last_status}}
							</div>
						</div>

						<button type="button" class="btn btn-sm btn-outline-secondary" title="Update now"
							method="POST" action="dns/dynamic/{{id}}/refresh" onclick="formAJAX()">
							<i class="fa-solid fa-rotate"></i>
						</button>
						<button type="button" class="btn btn-sm btn-outline-danger" title="Remove"
							method="DELETE" action="dns/dynamic/{{id}}" onclick="formAJAX()">
							<i class="fa-solid fa-trash-can"></i>
						</button>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>
</div>
<%- include('bottom') %>
