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 {IProductionNote} from '../../../../model/entities/production-note';
import {IProduction} from '../../../../model/entities/production';
import {ProductionNoteEditComponent} from '../production-note-edit/production-note-edit.component';
import {ProductionNoteDetailComponent} from '../production-note-detail/production-note-detail.component';

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

export class ProductionNoteViewComponent extends AgGridComponent implements OnInit {

    @Output() createNote: EventEmitter<IProductionNote> = new EventEmitter<IProductionNote>();
    @Output() editNote: EventEmitter<IProductionNote> = new EventEmitter<IProductionNote>();
    @Output() deleteNote: EventEmitter<number> = new EventEmitter<number>();
    @ViewChild('modalProductionNoteEdit', { static: true }) modalProductionNoteEdit: ModalComponent;
    @ViewChild('productionNoteEdit', { static: true }) productionNoteEdit: ProductionNoteEditComponent;
    @ViewChild('modalProductionNoteDetail', { static: true }) modalProductionNoteDetail: ModalComponent;
    @ViewChild('productionNoteDetail', { static: true }) productionNoteDetail: ProductionNoteDetailComponent;

    public production: IProduction;
    public productionNote: IProductionNote[];
    public productionNoteEntriesById: {};
    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.productionNote = [];
        this.productionNoteEntriesById = {};

        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 production
     * @param isUpdate
     */
    public setData(production: IProduction, isUpdate: boolean): void {
        this.production = production;
        this.productionNote = this.production.v_production_notes;
        this.productionNoteEntriesById = Utils.getSortedObjFromArray(this.productionNote, 'id');
        this.modalProductionNoteEdit.closeModal();
        this.generateEntries();
        if (isUpdate) {
            this.productionNoteDetail.updateData(production);
        } else {
            this.modalProductionNoteDetail.closeModal();
        }
    }

    /**
     * Generates AG grid entries
     */
    public generateEntries(): void {
        this.rowData = [];
        const items: {}[] = [];
        for (let i = 0; i < this.productionNote.length; i++) {
            let ccGender = '';
            if (this.productionNote[i].gender == 'male') {
                ccGender = 'Herr';
            } else if (this.productionNote[i].gender == 'female') {
                ccGender = 'Frau';
            } else if (this.productionNote[i].gender == 'diverse') {
                ccGender = 'Divers';
            }
            items.push({
                id: this.productionNote[i].id,
                date: this.productionNote[i].note_date,
                title: this.productionNote[i].title,
                comment: this.productionNote[i].comment,
                gender: ccGender,
                firstname: this.productionNote[i].firstname,
                lastname: this.productionNote[i].lastname,
                email: this.productionNote[i].email,
                phone_no: this.productionNote[i].phone_no,
                mobile_no: this.productionNote[i].mobile_no,
                fax_no: this.productionNote[i].fax_no,
                department: this.productionNote[i].department,
                creation_date: this.productionNote[i].creation_date,
                creator: this.productionNote[i].creation_user_firstname + ' ' + this.productionNote[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.modalProductionNoteDetail.openModal();
        this.productionNoteDetail.setData(this.production, this.productionNoteEntriesById[e.data.id]);
    }

    /**
     * On create click
     */
    public create(): void {
        this.modalProductionNoteEdit.openModal();
        this.productionNoteEdit.setData(this.production, Factory.getEmptyProductionNote(this.production.id, Utils.getCurrentDate()), true);
    }

    /**
     * Creates production note
     * @param productionNote
     */
    public createProductionNoteFunction(productionNote: IProductionNote): void {
        this.createNote.emit(productionNote);
    }

    /**
     * Edits note entry
     * @param productionNote
     */
    public editProductionNoteFunction(productionNote: IProductionNote) {
        this.editNote.emit(productionNote);
    }

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

}
