export class ActivityLog {

	public static ActivityLogsContainer: HTMLElement = document.querySelector("#activity-log-rows-container");
	/**
	 * Instance variables
	 */
	private Id: number;
	private CategoryID: number;
	private UserID: number;
	private Timestamp: number;
	private JsonData: string;
	private Username: string;
	private CategoryDescription: string;
	private TimeAgo: string;
	private Dom: HTMLElement;

	/**
	 * Takes an instance of Activity Log and appends it to Activity Logs Container in DOM.
	 * @param id 
	 * @param categoryId 
	 * @param userId 
	 * @param timestamp 
	 * @param jsonData 
	 * @param username 
	 * @param categoryDescription 
	 * @param timeAgo 
	 */
	public constructor(
		id: number,
		categoryId: number,
		userId: number,
		timestamp: number,
		jsonData: string,
		username: string,
		categoryDescription: string,
		timeAgo: string
	) {
		this.Id = id;
		this.CategoryID = categoryId;
		this.UserID = userId;
		this.Timestamp = timestamp;
		this.JsonData = jsonData;
		this.Username = username;
		this.CategoryDescription = categoryDescription;
		this.TimeAgo = timeAgo;
		this.Dom = this.GetDom();

		ActivityLog.ActivityLogsContainer.append(this.Dom);
	}

	/**
	 * Build HTML for component.
	 * @returns
	 */
	public GetDom() {
		let timeOfLogAction = new Date(this.Timestamp * 1000);
		let formattedTimeOfLogAction = timeOfLogAction.toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" });

		/**
		 * Activity Log Row element holds HTML structure.
		 */
		const template = document.createElement("activity-log-row");
		let jsonDataObject = JSON.parse(this.JsonData);
		let collapseAnchor = "";
		let content = "";

		if (Object.keys(jsonDataObject).length === 0) {
			console.log("No valid data to display for this entry");
		} else {
			collapseAnchor = `
				<a class="text-decoration-none" data-bs-toggle="collapse" href="#collapse${this.Id}" id="test${this.Id}">
					Show Data
				</a>
			`;
			for (const [key, value] of Object.entries(jsonDataObject)) {
				content += `
					<div>
						<strong>${key}</strong>: ${value}
					</div>
				`;
			}
		}

		template.innerHTML = `
			<div class="row py-2 border-top activity-log category-${this.CategoryID}">
				<div class="col-xl" style="max-width: 175px;">
					${formattedTimeOfLogAction}
				</div>
				<div class="col-xl d-flex flex-column">
					<div>
						<span>${this.Username}</span> <em>${this.CategoryDescription}</em> <span>${this.TimeAgo}</span>
					</div>
					<div class="data-container">
						${collapseAnchor}
						<div class="collapse" id="collapse${this.Id}">
							${content}
						</div>
					</div>
				</div>
			</div>
		`;

		/**
		 * Generated template is returned and stored in DOM.
		 */
		return template;
	}
}