import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AgGridComponent} from '../../../../components/ag-grid-component';
import {ModalComponent} from '../../../../components/modal/modal.component';
import {AppService} from '../../../../services/app.service';
import {Const} from '../../../../utils/const';
import {Factory} from '../../../../factory/factory';
import {Utils} from '../../../../utils/utils';
import {IServiceNote} from '../../../../model/entities/service-note';
import {IService} from '../../../../model/entities/service';
import {ServiceNoteEditComponent} from '../service-note-edit/service-note-edit.component';
import {ServiceNoteDetailComponent} from '../service-note-detail/service-note-detail.component';

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

export class ServiceNoteViewComponent extends AgGridComponent implements OnInit {

    @Output() createNote: EventEmitter<IServiceNote> = new EventEmitter<IServiceNote>();
    @Output() editNote: EventEmitter<IServiceNote> = new EventEmitter<IServiceNote>();
    @Output() deleteNote: EventEmitter<number> = new EventEmitter<number>();
    @ViewChild('modalServiceNoteEdit', { static: true }) modalServiceNoteEdit: ModalComponent;
    @ViewChild('serviceNoteEdit', { static: true }) serviceNoteEdit: ServiceNoteEditComponent;
    @ViewChild('modalServiceNoteDetail', { static: true }) modalServiceNoteDetail: ModalComponent;
    @ViewChild('serviceNoteDetail', { static: true }) serviceNoteDetail: ServiceNoteDetailComponent;

    public service: IService;
    public serviceNote: IServiceNote[];
    public serviceNoteEntriesById: {};
    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.serviceNote = [];
        this.serviceNoteEntriesById = {};

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

        this.columnDefs = [
            {headerName: 'Erstellungsdatum', field: 'creation_date', cellRenderer: this.dateRenderer, comparator: this.dateComparator },
            {headerName: 'Ersteller', field: 'creator'},
            {headerName: 'Datum', field: 'date', cellRenderer: this.dateRenderer, comparator: this.dateComparator },
            {headerName: 'Betreff', field: 'title' },
            {headerName: 'Notiz', field: 'comment' },
            {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' },
        ];
    }

    /**
     * Sets data
     * @param service
     * @param isUpdate
     */
    public setData(service: IService, isUpdate: boolean): void {
        this.service = service;
        this.serviceNote = this.service.v_service_notes;
        this.serviceNoteEntriesById = Utils.getSortedObjFromArray(this.serviceNote, 'id');
        this.modalServiceNoteEdit.closeModal();
        this.generateEntries();
        if (isUpdate) {
            this.serviceNoteDetail.updateData(service);
        } else {
            this.modalServiceNoteDetail.closeModal();
        }
    }

    /**
     * Generates AG grid entries
     */
    public generateEntries(): void {
        this.rowData = [];
        const items: {}[] = [];
        for (let i = 0; i < this.serviceNote.length; i++) {
            let ccGender = '';
            if (this.serviceNote[i].gender == 'male') {
                ccGender = 'Herr';
            } else if (this.serviceNote[i].gender == 'female') {
                ccGender = 'Frau';
            } else if (this.serviceNote[i].gender == 'diverse') {
                ccGender = 'Divers';
            }
            items.push({
                id: this.serviceNote[i].id,
                date: this.serviceNote[i].note_date,
                title: this.serviceNote[i].title,
                comment: this.serviceNote[i].comment,
                gender: ccGender,
                firstname: this.serviceNote[i].firstname,
                lastname: this.serviceNote[i].lastname,
                email: this.serviceNote[i].email,
                phone_no: this.serviceNote[i].phone_no,
                mobile_no: this.serviceNote[i].mobile_no,
                fax_no: this.serviceNote[i].fax_no,
                department: this.serviceNote[i].department,
                creation_date: this.serviceNote[i].creation_date,
                creator: this.serviceNote[i].creation_user_firstname + ' ' + this.serviceNote[i].creation_user_lastname,
            });
            this.rowData = items.sort((a: {} , b: {}) => this.dateComparator(a['date'], b['date'], false));
        }
    }

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

    /**
     * On create click
     */
    public create(): void {
        this.modalServiceNoteEdit.openModal();
        this.serviceNoteEdit.setData(this.service, Factory.getEmptyServiceNote(this.service.id, Utils.getCurrentDate()), true);
    }

    /**
     * Creates service note
     * @param serviceNote
     */
    public createServiceNoteFunction(serviceNote: IServiceNote): void {
        this.createNote.emit(serviceNote);
    }

    /**
     * Edits note entry
     * @param serviceNote
     */
    public editServiceNoteFunction(serviceNote: IServiceNote) {
        this.editNote.emit(serviceNote);
    }

    /**
     * Deletes service note
     * @param noteId
     */
    public deleteServiceNoteFunction(noteId: number): void {
        this.deleteNote.emit(noteId);
    }

}
