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 {IService} from '../../../../model/entities/service';
import {ServiceDataEditComponent} from '../service-data-edit/service-data-edit.component';

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

export class ServiceDataViewComponent implements OnInit {

    @Output() editService: EventEmitter<IService> = new EventEmitter<IService>();
    @ViewChild('modalServiceDataEdit', { static: true }) modalServiceDataEdit: ModalComponent;
    @ViewChild('serviceDataEdit', { static: true }) serviceDataEdit: ServiceDataEditComponent;

    public service: IService;
    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_PRODUCTION) ||
            this.appService.userHasRole(Const.USER_ROLE_SERVICE);
        this.config = this.appService.getConfig();
        this.service = Factory.getEmptyService();
        this.checkedUrl = '';
    }

    /**
     * Sets data
     * @param service
     */
    public setData(service: IService): void {
        this.service = service;
        this.checkedUrl = Utils.checkUrl(this.service.url);
        this.modalServiceDataEdit.closeModal();
    }

    /**
     * On edit click
     */
    public edit(): void {
        this.modalServiceDataEdit.openModal();
        this.serviceDataEdit.setData(Utils.deepClone(this.service) as IService);
    }

    /**
     * Saves service
     * @param service
     */
    public editServiceFunction(service: IService): void {
        this.editService.emit(service);
    }

}
