import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AgGridComponent} from '../../../../components/ag-grid-component';
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 {isNull} from 'util';
import {IServiceContact} from '../../../../model/entities/service-contact';
import {IService} from '../../../../model/entities/service';
import {
    ServiceContactPersonEditComponent
} from '../service-contact-person-edit/service-contact-person-edit.component';
import {
    ServiceContactPersonDetailComponent
} from '../service-contact-person-detail/service-contact-person-detail.component';

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

export class ServiceContactPersonViewComponent extends AgGridComponent implements OnInit {

    @Output() createServiceContact: EventEmitter<IServiceContact> = new EventEmitter<IServiceContact>();
    @Output() editServiceContact: EventEmitter<IServiceContact> = new EventEmitter<IServiceContact>();
    @Output() deleteServiceContact: EventEmitter<number> = new EventEmitter<number>();
    @Output() shortcut: EventEmitter<IService> = new EventEmitter<IService>();
    @ViewChild('modalServiceContactPersonEdit', { static: true }) modalServiceContactPersonEdit: ModalComponent;
    @ViewChild('serviceContactPersonEdit', { static: true }) serviceContactPersonEdit: ServiceContactPersonEditComponent;
    @ViewChild('modalServiceContactPersonDetail', { static: true }) modalServiceContactPersonDetail: ModalComponent;
    @ViewChild('serviceContactPersonDetail', { static: true }) serviceContactPersonDetail: ServiceContactPersonDetailComponent;

    public service: IService;
    public serviceContacts: IServiceContact[];
    public serviceContactsById: {};
    public config: IConfig;
    public hasEditRights: boolean;

    constructor(private appService: AppService) {
        super();
    }

    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.serviceContacts = [];
        this.serviceContactsById = {};

        this.defaultColDef = {
            resizable: true,
            sortable: true
        };

        this.columnDefs = [
            {headerName: 'Anrede', field: 'gender', width: 90 },
            {headerName: 'Vorname', field: 'firstname' },
            {headerName: 'Nachname', field: 'lastname' },
            {headerName: 'Abteilung', field: 'department' },
            {headerName: 'E-Mail Adresse', field: 'email', cellRenderer: this.emailRenderer },
            {headerName: 'Telefon', field: 'phone_no', cellRenderer: this.phoneRenderer },
            {headerName: 'Mobil', field: 'mobile_no', cellRenderer: this.phoneRenderer },
            {headerName: 'Fax', field: 'fax_no' },
            {headerName: 'Straße', field: 'street' },
            {headerName: 'Hausnummer', field: 'street_no' },
            {headerName: 'PLZ', field: 'zip' },
            {headerName: 'Ort', field: 'city' },
            {headerName: 'Land', field: 'country' },
            {headerName: 'Bemerkungen', field: 'comment' }
        ];
    }

    /**
     * Sets data
     * @param service
     * @param isUpdate
     */
    public setData(service: IService, isUpdate: boolean): void {
        this.service = service;
        this.serviceContacts = this.service.v_service_contacts;
        this.serviceContactsById = Utils.getSortedObjFromArray(this.serviceContacts, 'id');
        this.modalServiceContactPersonEdit.closeModal();
        this.generateEntries();
        if (isUpdate) {
            this.serviceContactPersonDetail.updateData(service);
        } else {
            this.modalServiceContactPersonDetail.closeModal();
        }
    }

    /**
     * Generates AG grid entries
     */
    public generateEntries(): void {
        this.rowData = [];
        for (let i = 0; i < this.serviceContacts.length; i++) {
            let ocGender: string;
            if (this.serviceContacts[i].gender == 'male') {
                ocGender = 'Herr';
            } else if (this.serviceContacts[i].gender == 'female') {
                ocGender = 'Frau';
            } else {
                ocGender = 'Divers';
            }
            this.rowData.push({
                id: this.serviceContacts[i].id,
                gender: ocGender,
                firstname: this.serviceContacts[i].firstname,
                lastname: this.serviceContacts[i].lastname,
                department: this.serviceContacts[i].department,
                email: this.serviceContacts[i].email,
                phone_no: this.serviceContacts[i].phone_no,
                mobile_no: this.serviceContacts[i].mobile_no,
                fax_no: this.serviceContacts[i].fax_no,
                street: this.serviceContacts[i].street,
                street_no: this.serviceContacts[i].street_no,
                zip: this.serviceContacts[i].zip,
                city: this.serviceContacts[i].city,
                country: !isNull(this.serviceContacts[i].country_id) ? this.config.vc_countries_by_id[this.serviceContacts[i].country_id].name : null,
                comment: this.serviceContacts[i].comment,
            });
        }
    }

    /**
     * On row click
     * @param e
     */
    public rowClicked(e: any) {
        this.modalServiceContactPersonDetail.openModal();
        this.serviceContactPersonDetail.setData(this.service, Utils.deepClone(this.serviceContactsById[e.data.id]) as IServiceContact);
    }

    /**
     * On create click
     */
    public create(): void {
        this.modalServiceContactPersonEdit.openModal();
        this.serviceContactPersonEdit.setData(Factory.getEmptyServiceContact(this.service.id));
    }

    /**
     * Creates service contact
     * @param serviceContact
     */
    public createServiceContactFunction(serviceContact: IServiceContact): void {
        this.createServiceContact.emit(serviceContact);
    }

    /**
     * Edit service contact
     * @param serviceContact
     */
    public editServiceContactFunction(serviceContact: IServiceContact): void {
        this.editServiceContact.emit(serviceContact);
    }

    /**
     * Deletes service contact
     * @param serviceId
     */
    public deleteServiceContactFunction(serviceId: number): void {
        this.deleteServiceContact.emit(serviceId);
    }

    /**
     * Shortcut to service detail
     * @param service
     */
    public shortcutFunction(service: IService): void {
        this.modalServiceContactPersonDetail.closeModal();
        this.shortcut.emit(service);
    }

}
