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 {IProductionMeeting} from '../../../../model/entities/production-meeting';
import {ProductionMeetingEditComponent} from '../production-meeting-edit/production-meeting-edit.component';
import {ProductionMeetingDetailComponent} from '../production-meeting-detail/production-meeting-detail.component';
import {IProduction} from '../../../../model/entities/production';

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

export class ProductionMeetingViewComponent extends AgGridComponent implements OnInit, OnDestroy {

    @Output() createMeeting: EventEmitter<IProductionMeeting> = new EventEmitter<IProductionMeeting>();
    @Output() editMeeting: EventEmitter<IProductionMeeting> = new EventEmitter<IProductionMeeting>();
    @Output() deleteMeeting: EventEmitter<number> = new EventEmitter<number>();
    @Output() editMeetingReport: EventEmitter<any> = new EventEmitter<any>();
    @ViewChild('modalProductionMeetingEdit', {static: true}) modalProductionMeetingEdit: ModalComponent;
    @ViewChild('productionMeetingEdit', {static: true}) productionMeetingEdit: ProductionMeetingEditComponent;
    @ViewChild('modalProductionMeetingDetail', {static: true}) modalProductionMeetingDetail: ModalComponent;
    @ViewChild('productionMeetingDetail', {static: true}) productionMeetingDetail: ProductionMeetingDetailComponent;

    public production: IProduction;
    public productionMeeting: IProductionMeeting[];
    public productionMeetingEntriesById: {};
    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.production = Factory.getEmptyProduction();
        this.productionMeeting = [];
        this.productionMeetingEntriesById = {};
        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: 'productionContactName'},
            {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 production
     * @param isUpdate
     */
    public setData(production: IProduction, isUpdate: boolean): void {
        this.production = production;
        this.productionMeeting = this.production.v_production_meetings;
        this.productionMeetingEntriesById = Utils.getSortedObjFromArray(this.productionMeeting, 'id');
        this.modalProductionMeetingEdit.closeModal();
        this.generateEntries();
        if (isUpdate) {
            this.productionMeetingDetail.updateData(production);
        } else {
            this.modalProductionMeetingDetail.closeModal();
        }
    }

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

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

            items.push({
                that: this,
                id: this.productionMeeting[i].id,
                title: this.productionMeeting[i].title,
                date: this.productionMeeting[i].start_date,
                time_start: this.productionMeeting[i].start_date,
                time_end: this.productionMeeting[i].end_date,
                type: this.meetingType.name,
                typeType: this.meetingType.type,
                street: this.productionMeeting[i].street,
                street_no: this.productionMeeting[i].street_no,
                zip: this.productionMeeting[i].zip,
                city: this.productionMeeting[i].city,
                owner: this.owner.firstname + ' ' + this.owner.lastname,
                creator: creator.firstname + ' ' + creator.lastname,
                productionContactName,
                participants: this.productionMeeting[i].v_participants,
                department: this.productionMeeting[i].department,
                email: this.productionMeeting[i].email,
                phone: this.productionMeeting[i].phone_no,
                mobile: this.productionMeeting[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.modalProductionMeetingDetail.openModal();
        this.productionMeetingDetail.setData(this.production, this.productionMeetingEntriesById[e.data.id]);
    }

    /**
     * On create click
     */
    public create(): void {
        this.modalProductionMeetingEdit.openModal();
        this.productionMeetingEdit.setData(this.production, Factory.getEmptyProductionMeeting(this.production.id), true);
    }

    /**
     * Creates production meeting
     * @param productionMeeting
     */
    public createProductionMeetingFunction(productionMeeting: IProductionMeeting): void {
        this.createMeeting.emit(productionMeeting);
    }

    /**
     * Edits meeting entry
     * @param productionMeeting
     */
    public editProductionMeetingFunction(productionMeeting: IProductionMeeting) {
        this.editMeeting.emit(productionMeeting);
    }

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

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

    ngOnDestroy(): void {

    }

}
