import { Component, OnInit, Input } from '@angular/core'

interface Block {
	id: number;
	created: string;
	title: string;
	modified: string;
	customFields: [
		{
			identifier: string;
			value: string;
		}
	]
	content: string;
	image: {
		thumbnail: string;
		medium: string;
		large: string;
		full: string;
	}
}

@Component({
	selector: 'static-block-cookie-handler',
	templateUrl: './tpl.static-cookie-handler.pug'
})
export class StaticBlockCookieHandler implements OnInit {

	// Variables ----
	@Input('static-block') staticBlock
	sortedBlock = {
		title: 'Cookies',
		content: 'This site uses cookies.',
		cta_label: 'OK',
		cta_secondary_label: 'read more',
		cta_secondary_url: '/cookies'
	}

	constructor() { }


	// Lifecycle hooks ----
	ngOnInit() { 
		this.sort(this.staticBlock)
	}


	// Functions ----

	/**
	 * Sorts through block content for `title`, `content`,
	 * `sortedBlock.cta_label`, `sortedBlock.cta_secondary_label`,
	 * and `cta_secondary_url`. These are then assigned to `sortedBlock`
	 * 
	 * @param block 
	 */
	sort(block: Block) {
		if(!!block.title.length) {
			this.sortedBlock.title = block.title
		}

		if(!!block.content) {
			this.sortedBlock.content = block.content
		}

		for(let i = 0; i < block.customFields.length; i++) {
			switch(block.customFields[i].identifier) {
				case 'cta_label':
					this.sortedBlock.cta_label = block.customFields[i].value
					break
				case 'cta_secondary_label':
					this.sortedBlock.cta_secondary_label = block.customFields[i].value
					break
				case 'cta_secondary_url':
					this.sortedBlock.cta_secondary_url = block.customFields[i].value
					break
			}
		}
	}


}