import {
	Component,
	ComponentFactoryResolver,
	ComponentRef,
	EventEmitter,
	Input,
	OnChanges,
	OnInit,
	SimpleChanges,
	ViewChild
} from '@angular/core';

// Директивы
import { CrmViewContainerDirective } from '../../directives';

// Ячейка таблицы
@Component({
	selector: 'crm-table-cell',
	templateUrl: './crm-table-cell.component.html',
	styleUrls: ['./crm-table-cell.component.scss']
})
export class CrmTableCellComponent implements OnInit, OnChanges {

	constructor(private readonly factoryResolver: ComponentFactoryResolver) {}

	// Компонент ячейки
	@Input() public is: any;

	// Данные ячейки
	@Input() public data: any;

	// Столбец
	@Input() public column: any;

	// Строка
	@Input() public row: any;

	// Событие изменения высоты ячейки
	@Input() public emitterChangeHeight: EventEmitter<any>;

	// Ссылка на директиву для доступа к viewContainerRef
	@ViewChild(CrmViewContainerDirective) public view: CrmViewContainerDirective;

	// Ссылка на компонент
	private componentRef: ComponentRef<any>;

	// Загрузка компонента
	private loadComponent(): void {
		const factory = this.factoryResolver.resolveComponentFactory(this.is);
		const viewContainerRef = this.view.viewContainerRef;

		if (viewContainerRef) {
			viewContainerRef.clear();
			this.componentRef = viewContainerRef.createComponent(factory);
			const instance = this.componentRef.instance as {
				data: any;
				column: any;
				row: any;
				emitterChangeHeight: EventEmitter<any>;
			};

			instance.data = this.data;
			instance.column = this.column;
			instance.row = this.row;
			instance.emitterChangeHeight = this.emitterChangeHeight;
		}
	}

	// --------------------------------------------------------------------------
	// HOOKS
	// Инициализация
	public ngOnInit(): void {
		this.loadComponent();
	}

	// Изменение входных параметров
	public ngOnChanges(changes: SimpleChanges): void {
		if (changes.data && this.componentRef && this.componentRef.instance) {
			this.componentRef.instance.data = this.data;
		}
	}
}
