<template>
<div id="statusBox">
  <div class="row">
		<div class="col-4">
			<select :ref="'serverSelectBox' + 1" v-if="pending === false" v-model="selectedServerData" id="serverSelectList">
				<option v-for="(serverItem, index) in serverlist" 
					v-bind:value="serverItem"
				>
					{{serverItem.getLabelInfoString()}}
				</option>
			</select>
			
			<input v-model="target" placeholder="Enter Ip or Domain">
			<button v-on:click="handleClick()">
				⛟
			</button>
<RingLoader :size="10" :loading="isLoading" color="black"></RingLoader>
			<br>
			
			<span class="small">{{infoString}}</span>
			<div>
				<table :id="'tableId_'+boxNumber" class="table table-striped">
					<thead>
						<tr>
							<td>IP</td>
							<td>HOSTNAME</td>
							<td>PING</td>
							<td>AS</td>
						</tr>
						<tr :class="isOdd(index)" v-for="(tData, index) in tableData">
							<td>{{ tData[0] }}</td>
							<td>{{ tData[1] }}</td>
							<td>{{ tData[2] }}</td>
							<td :title="tData[4]">{{ tData[3] }}</td>
						</tr>
					</thead>
				</table> 
					<input class="range" v-model="tick" type="range" v-if="tableDataHistory.length > 1" :max="tableDataHistory.length -1" min="0" :list="'tickmarks'+_uid">
					<datalist :id="'tickmarks'+_uid">
						<option v-for="(historyItem, index) in tableDataHistory" 
							:value="index"
						>
						</option>
					</datalist>
			</div>
		</div>
	</div>
</div>
</template>

<script>
import axios from 'axios';
import XtrServer from './ModelObjects/XtrServer.js';
import XtrData from './ModelObjects/XtrData.js';
import { RingLoader } from 'vue-spinners-css';

export default {
	components: {
		RingLoader
	},
	props: {
		serverlist: Array,
		pending: Boolean,
		boxNumber: Number,
		initData: XtrServer
	},
	data : function () {
		return {
			isLoading: false,
			executionTime: 'Not execute yet',
			selectedServerData: this.initData,
			tick: '',
			target: 'luan.xicon.eu',
			tableData : [ ],
			tableDataHistory: [],
			tableDataHistoryObject: [],
			jobCount: 0,
			jobList: []
		}
	},
	watch: {
		pending : {
			handler() {
				if(this.pending === false 
				&& this.serverlist.length > 0 
				&& !(JSON.parse(sessionStorage.getItem(this.selectedServerDataIndex)))
				) {
					this.selectedServerData = this.serverlist[0];
				}
			}
		},

		tableDataHistory : {
			handler() {
				sessionStorage.setItem('tableDataHistory' + this.boxNumber, JSON.stringify(this.tableDataHistory));
				// Restore history data and set the marker to the last range item
				this.tick = this.tableDataHistory.length -1;
			}
		},

		tableDataHistoryObject : {
			handler() {
				sessionStorage.setItem('tableDataHistoryObject' + this.boxNumber, JSON.stringify(this.tableDataHistoryObject));
				// Restore history data and set the marker to the last range item
				this.tick = this.tableDataHistoryObject.length -1;
			},
			deep: true
		},

		executionTime : {
			handler()  { 
				sessionStorage.setItem('executionTime' + this.boxNumber, JSON.stringify(this.executionTime));
			},
			deep: true
		}, 

		selectedServerData : {
			handler() {
				sessionStorage.setItem('selectedServerData' + this.boxNumber, JSON.stringify(this.selectedServerData));
			},
			deep: true
		},

		target : {
			handler() {
				sessionStorage.setItem('target' + this.boxNumber, JSON.stringify(this.target));
			},
			deep: true
		},

		tableData : {
			handler() {
				sessionStorage.setItem(this.tableDataIndex, JSON.stringify(this.tableData));
			},
			deep: true
		},

		tick : {
			handler() {
				sessionStorage.setItem(this.tickIndex, JSON.stringify(this.tick));
				if(this.tableDataHistory.length > 0) {
					this.tableData = this.tableDataHistory[this.tick];
				}
				
			}
		}
	},
	computed : {
		selectedServerDataIndex : function selectedServerDataIndex() {
			return 'selectedServerData' + this.boxNumber;
		},

		tickIndex: function tickIndex() {
			return 'tick' + this.boxNumber;
		},

		tableDataIndex : function tableDataIndex() {
			return 'tableData' + this.boxNumber;
		},

		infoString : function infoString() {
			var obData = this.tableDataHistoryObject[this.tick];
			if(typeof(obData) !== "undefined" && obData !== null){
				return obData.displayInfo();
			} else {
				return '';
			}
		},

		tryHard : function tryHard() {
			if (this.selectedServerData) {

			} else {
				this.selectedServerData = this.initData;
			}
		}
	},
	methods : {
		isOdd : function isOdd(index) {
			if(index % 2 === 0) {
				return 'odd';
			} else {
				return 'even';
			}
		},

		handleClick: function handleClick() {
			this.traceRoute();			
		},

		setLastExecutionTime : function setLastExecutionTime() {
			var day = new Date();
			this.executionTime = day.toISOString()
			
		},
		
		traceRoute : function traceRoute() {
			this.isLoading = true;
			let jobId = this.getJobCount;
			this.jobList.push(jobId);
			// e.g. http://199.247.22.146:12111/v3/client/request/8.8.8.8
			axios.get("http://" + this.selectedServerData.getIpPortAsString() + "/v3/client/request/" + this.target)
				.then(response => {
					// JSON responses are automatically parsed.
					this.tableData = response.data;
					this.setLastExecutionTime();
					this.tableDataHistory.push(this.tableData);
					this.tick = this.tableDataHistory.length -1;
					var xtrData = new XtrData();
					xtrData.initObjectByElements(this.selectedServerData, this.executionTime , this.tableData ,this.target);
					this.tableDataHistoryObject.push(xtrData);
				})
				.catch(e => {
					if(e.response !== undefined) {
						// JSON responses are automatically parsed.
						this.tableData = {0 : {
							0: "Status-Code: HTTP/" + e.response.status,
							1: "Message: " + e.response.statusText,
							2: "",
							3: "",
							4: ""
						}};
						this.setLastExecutionTime();
						this.tableDataHistory.push(this.tableData);
						this.tick = this.tableDataHistory.length -1;
						var xtrData = new XtrData();
						xtrData.initObjectByElements(this.selectedServerData, this.executionTime , this.tableData ,this.target);
						this.tableDataHistoryObject.push(xtrData);
					}
				}).finally(ee => { 
					var position = this.jobList.indexOf(jobId);

					if(~position) {
						this.jobList.splice(position, 1);
					} 
					if(this.jobList.length < 1) {
						this.jobCount = 0;
						this.isLoading = false;
					}
				});
				
		},

		getJobCount : function getJobCount() {
			this.jobCount += 1;
			return this.jobCount;
		},

		resetData : function resetData() {
			this.executionTime =  'Not execute yet';
			this.target =  'luan.xicon.eu';
			this.tableData =  [ ];
			this.tableDataHistory = [ ];
			this.tableDataHistoryObject = [ ];
			this.selectedServerData = this.serverlist[0];
			this.tick = '';
		}
	},
	mounted() {
		if (sessionStorage.getItem('tableDataHistory'+ this.boxNumber)) this.tableDataHistory = JSON.parse(sessionStorage.getItem('tableDataHistory'+ this.boxNumber));
		if (sessionStorage.getItem('tick'+ this.boxNumber)) this.tick = parseInt(sessionStorage.getItem('tick'+ this.boxNumber));
		if (sessionStorage.getItem('executionTime'+ this.boxNumber)) this.executionTime = JSON.parse(sessionStorage.getItem('executionTime'+ this.boxNumber));
		
		if (sessionStorage.getItem('tableDataHistoryObject'+ this.boxNumber)) {
			
			var manA = JSON.parse(sessionStorage.getItem('tableDataHistoryObject'+ this.boxNumber));
			manA.forEach(element => {
				var restoreData = new XtrData();
				var restoreServer = new XtrServer();
				
				restoreServer.initObjectByJson(element._requestServer);
				restoreData.initObjectByElements(restoreServer, element._requestSendTime, element._responseData, element._targetUrl);
				this.tableDataHistoryObject.push(restoreData);
			});
		}
		if (sessionStorage.getItem('selectedServerData'+ this.boxNumber)) {
			var restoreData = new XtrServer();
			var man = JSON.parse(sessionStorage.getItem('selectedServerData'+ this.boxNumber))
			restoreData.initObjectByJson(man);
			this.selectedServerData = restoreData;
		}

		if (sessionStorage.getItem('target'+ this.boxNumber)) this.target = JSON.parse(sessionStorage.getItem('target'+ this.boxNumber));
		if (sessionStorage.getItem('tableData'+ this.boxNumber)) this.tableData = JSON.parse(sessionStorage.getItem('tableData'+ this.boxNumber));
	}
}
</script>

<style scoped>
	input[type=range] {
		width: 90%;
		display: flex;
		flex-direction: column;
		align-items: stretch;
	}

	span.small {
		font-size: 75%;
	}

	table.active {
		border: 3px solid #9ac5e3;
	}

	table {
		border-collapse: collapse;
		width: 90%;
	}

	td {
		border:1px solid grey;
		font-size: 9pt;
	}

	.traceroutes {
		text-decoration: none;
		display: inline-block;
	}

	.traceroutes:visited {
		color: #000000;
	}

	.traceroutes:hover {
		color: #880000;
		transform: rotate(-30deg);
	}

	.traceroutes:active {
		color: #bb0000;
	}

	.traceroutes_rotating {
		display: inline-block;
		text-decoration: none;
		color: #bb0000;
		animation: spin 2s linear infinite;
	}

	.odd {
		background-color: #EEE;
	}

	@keyframes spin {
		0% { transform: rotate(-30deg); }
		25% { transform: rotate(0deg); }
		50% { transform: rotate(30deg); } 
		75% { transform: rotate(0deg); }
		100% { transform: rotate(-30deg); }
	}	
</style>