import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AgGridComponent} from '../../../components/ag-grid-component';
import {ModalComponent} from '../../../components/modal/modal.component';
import {Utils} from '../../../utils/utils';
import {Const} from '../../../utils/const';
import {AppService} from '../../../services/app.service';
import {CommonService} from '../../../services/common.service';
import {IService} from '../../../model/entities/service';
import {IServiceContact} from '../../../model/entities/service-contact';
import {
    ServiceContactPersonDetailComponent
} from '../service-view/service-contact-person-detail/service-contact-person-detail.component';
import {ServiceService} from '../../../services/service.service';

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

export class ServicesContactListComponent extends AgGridComponent implements OnInit {

    @Output() shortcut: EventEmitter<IService> = new EventEmitter<IService>();
    @ViewChild('modalServicesContactPersonDetailList', { static: true }) modalServicesContactPersonDetailList: ModalComponent;
    @ViewChild('serviceContactPersonDetailList', { static: true }) serviceContactPersonDetailList: ServiceContactPersonDetailComponent;

    public services: IService[];
    public servicesById: {};
    private serviceContacts: IServiceContact[];
    public serviceContactsById: {};
    public hasAdminRights: boolean;
    public hasExportRights: boolean;

    constructor(public appService: AppService, private serviceService: ServiceService, private commonService: CommonService) {
        super();
    }

    ngOnInit() {
        this.hasAdminRights = this.appService.userHasRole(Const.USER_ROLE_ADMIN);
        this.hasExportRights = this.appService.userHasRole(Const.USER_ROLE_ADMIN);
        this.services = [];
        this.servicesById = {};
        this.serviceContacts = [];
        this.serviceContactsById = {};

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

        this.columnDefs = [
            {headerName: 'ID', field: 'id', width: 60 },
            {headerName: 'Service-Dienstleister ID', field: 'service_id', width: 100 },
            {headerName: 'Service-Dienstleister', field: 'service' },
            {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: 'Bemerkungen', field: 'comment' }
        ];

        this.rowSelection = 'single';
    }

    /**
     * Sets data
     * @param services
     * @param serviceContacts
     */
    public setData(services: IService[], serviceContacts: IServiceContact[]): void {
        this.services = services;
        this.servicesById = Utils.getSortedObjFromArray(this.services, 'id');
        this.serviceContacts = serviceContacts;
        this.serviceContactsById = Utils.getSortedObjFromArray(this.serviceContacts, 'id');
        this.generateEntries();
    }

    /**
     * Generates AG grid entries for services grid
     */
    public generateEntries(): void {
        this.rowData = [];

        for (let i = 0; i < this.serviceContacts.length; i++) {
            this.rowData.push({
                id: this.serviceContacts[i].id,
                service_id: this.serviceContacts[i].service_id,
                service: this.servicesById[this.serviceContacts[i].service_id].name,
                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,
                comment: this.serviceContacts[i].comment
            });
        }
    }

    /**
     * Row is clicked
     * @param e
     */
    public rowClicked(e: any) {
        this.modalServicesContactPersonDetailList.openModal();
        this.serviceContactPersonDetailList.setData(this.servicesById[e.data.service_id], Utils.deepClone(this.serviceContactsById[e.data.id]) as IServiceContact);
    }

    /**
     * Edit service contact
     * @param serviceContact
     */
    public editServiceContactFunction(serviceContact: IServiceContact): void {
        this.serviceService.apiEditServiceContact(serviceContact).subscribe(
            data => {
                this.serviceContactPersonDetailList.updateData(data.result_data as IService);
            },
            error => {}
        );
    }

    /**
     * Delete service contact
     * @param serviceId
     */
    public deleteServiceContactFunction(serviceId: number): void {
        this.serviceService.apiDeleteServiceContact(serviceId).subscribe(
            data => {
                this.modalServicesContactPersonDetailList.closeModal();
            },
            error => {}
        );
    }

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

    /**
     * Export service contacts pdf
     */
    public exportServiceContactsPdf(): void {
        this.commonService.apiExportContactsPdf('Service_Kontakte', 'service');
    }

    /**
     * Export service xmas pdf
     */
    public exportXmasPdf(): void {
        this.commonService.apiExportXmasPdf('Produzent_Weihnachten', 'service');
    }
}
