import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {ModalComponent} from '../../../../components/modal/modal.component';
import {IConfig} from '../../../../model/virtual/config';
import {AppService} from '../../../../services/app.service';
import {Const} from '../../../../utils/const';
import {Factory} from '../../../../factory/factory';
import {Utils} from '../../../../utils/utils';
import {IOperator} from '../../../../model/entities/operator';
import {OperatorDataEditComponent} from '../operator-data-edit/operator-data-edit.component';

@Component({
  selector: 'app-operator-data-view',
  templateUrl: './operator-data-view.component.html',
  styleUrls: ['./operator-data-view.component.scss']
})

export class OperatorDataViewComponent implements OnInit {

    @Output() editOperator: EventEmitter<IOperator> = new EventEmitter<IOperator>();
    @ViewChild('modalOperatorDataEdit', { static: true }) modalOperatorDataEdit: ModalComponent;
    @ViewChild('operatorDataEdit', { static: true }) operatorDataEdit: OperatorDataEditComponent;

    public operator: IOperator;
    public checkedUrl: string;
    public config: IConfig;
    public hasEditRights: boolean;

    constructor(private appService: AppService) { }

    ngOnInit() {
        this.hasEditRights =
            this.appService.userHasRole(Const.USER_ROLE_TECHNIQUE) ||
            this.appService.userHasRole(Const.USER_ROLE_ACCOUNTING);
        this.config = this.appService.getConfig();
        this.operator = Factory.getEmptyOperator();
        this.checkedUrl = '';
    }

    /**
     * Sets data
     * @param operator
     */
    public setData(operator: IOperator): void {
        this.operator = operator;
        this.checkedUrl = Utils.checkUrl(this.operator.url);
        this.modalOperatorDataEdit.closeModal();
    }

    /**
     * On edit click
     */
    public edit(): void {
        this.modalOperatorDataEdit.openModal();
        this.operatorDataEdit.setData(Utils.deepClone(this.operator) as IOperator);
    }

    /**
     * Saves operator
     * @param operator
     */
    public editOperatorFunction(operator: IOperator): void {
        this.editOperator.emit(operator);
    }

}
