import {Component, EventEmitter, OnDestroy, OnInit, Output, ViewChild} from '@angular/core';
import {AgGridComponent} from '../../../../components/ag-grid-component';
import {ModalComponent} from '../../../../components/modal/modal.component';
import {IUser} from '../../../../model/entities/user';
import {IMeetingType} from '../../../../model/entities/meeting-type';
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 {IServiceMeeting} from '../../../../model/entities/service-meeting';
import {ServiceMeetingEditComponent} from '../service-meeting-edit/service-meeting-edit.component';
import {ServiceMeetingDetailComponent} from '../service-meeting-detail/service-meeting-detail.component';
import {IService} from '../../../../model/entities/service';

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

export class ServiceMeetingViewComponent extends AgGridComponent implements OnInit, OnDestroy {

    @Output() createMeeting: EventEmitter<IServiceMeeting> = new EventEmitter<IServiceMeeting>();
    @Output() editMeeting: EventEmitter<IServiceMeeting> = new EventEmitter<IServiceMeeting>();
    @Output() deleteMeeting: EventEmitter<number> = new EventEmitter<number>();
    @Output() editMeetingReport: EventEmitter<any> = new EventEmitter<any>();
    @ViewChild('modalServiceMeetingEdit', {static: true}) modalServiceMeetingEdit: ModalComponent;
    @ViewChild('serviceMeetingEdit', {static: true}) serviceMeetingEdit: ServiceMeetingEditComponent;
    @ViewChild('modalServiceMeetingDetail', {static: true}) modalServiceMeetingDetail: ModalComponent;
    @ViewChild('serviceMeetingDetail', {static: true}) serviceMeetingDetail: ServiceMeetingDetailComponent;

    public service: IService;
    public serviceMeeting: IServiceMeeting[];
    public serviceMeetingEntriesById: {};
    public owner: IUser;
    public participants: IUser[];
    public meetingType: IMeetingType;
    public date: string;
    public timeStart: string;
    public timeEnd: string;
    public hasEditRights: boolean;

    constructor(public 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.service = Factory.getEmptyService();
        this.serviceMeeting = [];
        this.serviceMeetingEntriesById = {};
        this.owner = Factory.getEmptyUser();
        this.participants = [];
        this.meetingType = Factory.getEmptyMeetingType();
        this.date = '';
        this.timeStart = '';
        this.timeEnd = '';

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

        this.columnDefs = [
            {headerName: 'Datum', field: 'date', cellRenderer: this.dateRenderer, comparator: this.dateComparator},
            {headerName: 'Ersteller', field: 'creator' },
            {headerName: 'PLP Verantwortlicher', field: 'owner'},
            {headerName: 'Gesprächspartner', field: 'serviceContactName'},
            {headerName: 'Titel', field: 'title'},
            {headerName: 'Uhrzeit (Start)', field: 'time_start', cellRenderer: this.timeRenderer},
            {headerName: 'Uhrzeit (Ende)', field: 'time_end', cellRenderer: this.timeRenderer},
            {headerName: 'Termin-Art', field: 'type'},
            {headerName: 'Adresse', field: 'address', cellRenderer: this.addressRenderer, autoHeight: true},
            {
                headerName: 'Teilnehmer',
                field: 'participants',
                cellRenderer: this.participantsRenderer,
                autoHeight: true
            },
            {headerName: 'Abteilung', field: 'department'},
            {headerName: 'E-Mail', field: 'email'},
            {headerName: 'Telefon', field: 'phone'},
            {headerName: 'Mobil', field: 'mobile'},
        ];
    }

    /**
     * Sets data
     * @param service
     * @param isUpdate
     */
    public setData(service: IService, isUpdate: boolean): void {
        this.service = service;
        this.serviceMeeting = this.service.v_service_meetings;
        this.serviceMeetingEntriesById = Utils.getSortedObjFromArray(this.serviceMeeting, 'id');
        this.modalServiceMeetingEdit.closeModal();
        this.generateEntries();
        if (isUpdate) {
            this.serviceMeetingDetail.updateData(service);
        } else {
            this.modalServiceMeetingDetail.closeModal();
        }
    }

    /**
     * Generates AG grid entries
     */
    public generateEntries(): void {
        this.rowData = [];
        const items: {}[] = [];
        for (let i = 0; i < this.serviceMeeting.length; i++) {

            this.owner = this.appService.getConfig().vc_user_by_id[this.serviceMeeting[i].owner_user_id];
            this.meetingType = this.appService.getConfig().vc_meeting_types_by_id[this.serviceMeeting[i].meeting_type_id];
            let serviceContactName: string = !isNull(this.serviceMeeting[i].firstname) ? this.serviceMeeting[i].firstname + ' ' : '';
            serviceContactName += !isNull(this.serviceMeeting[i].lastname) ? this.serviceMeeting[i].lastname : '';
            const creator: IUser = this.appService.getConfig().vc_user_by_id[this.serviceMeeting[i].creation_user_id];

            items.push({
                that: this,
                id: this.serviceMeeting[i].id,
                title: this.serviceMeeting[i].title,
                date: this.serviceMeeting[i].start_date,
                time_start: this.serviceMeeting[i].start_date,
                time_end: this.serviceMeeting[i].end_date,
                type: this.meetingType.name,
                typeType: this.meetingType.type,
                street: this.serviceMeeting[i].street,
                street_no: this.serviceMeeting[i].street_no,
                zip: this.serviceMeeting[i].zip,
                city: this.serviceMeeting[i].city,
                owner: this.owner.firstname + ' ' + this.owner.lastname,
                creator: creator.firstname + ' ' + creator.lastname,
                serviceContactName,
                participants: this.serviceMeeting[i].v_participants,
                department: this.serviceMeeting[i].department,
                email: this.serviceMeeting[i].email,
                phone: this.serviceMeeting[i].phone_no,
                mobile: this.serviceMeeting[i].mobile_no,
            });
        }
        this.rowData = items.sort((a: {} , b: {}) => this.dateComparator(a['date'], b['date'], false));
    }

    /**
     * On row click
     * @param e
     */
    public rowClicked(e: any) {
        this.modalServiceMeetingDetail.openModal();
        this.serviceMeetingDetail.setData(this.service, this.serviceMeetingEntriesById[e.data.id]);
    }

    /**
     * On create click
     */
    public create(): void {
        this.modalServiceMeetingEdit.openModal();
        this.serviceMeetingEdit.setData(this.service, Factory.getEmptyServiceMeeting(this.service.id), true);
    }

    /**
     * Creates service meeting
     * @param serviceMeeting
     */
    public createServiceMeetingFunction(serviceMeeting: IServiceMeeting): void {
        this.createMeeting.emit(serviceMeeting);
    }

    /**
     * Edits meeting entry
     * @param serviceMeeting
     */
    public editServiceMeetingFunction(serviceMeeting: IServiceMeeting) {
        this.editMeeting.emit(serviceMeeting);
    }

    /**
     * Deletes service meeting
     * @param meetingId
     */
    public deleteServiceMeetingFunction(meetingId: number): void {
        this.deleteMeeting.emit(meetingId);
    }

    /**
     * Edit report after meeting has started
     * @param reportValues
     */
    public editServiceMeetingReportFunction(reportValues: any): void {
        this.editMeetingReport.emit(reportValues);
    }

    ngOnDestroy(): void {

    }

}
