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

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

export class CustomerNoteViewComponent extends AgGridComponent implements OnInit {

    @Output() createNote: EventEmitter<ICustomerNote> = new EventEmitter<ICustomerNote>();
    @Output() editNote: EventEmitter<ICustomerNote> = new EventEmitter<ICustomerNote>();
    @Output() deleteNote: EventEmitter<number> = new EventEmitter<number>();
    @ViewChild('modalCustomerNoteEdit', { static: true }) modalCustomerNoteEdit: ModalComponent;
    @ViewChild('customerNoteEdit', { static: true }) customerNoteEdit: CustomerNoteEditComponent;
    @ViewChild('modalCustomerNoteDetail', { static: true }) modalCustomerNoteDetail: ModalComponent;
    @ViewChild('customerNoteDetail', { static: true }) customerNoteDetail: CustomerNoteDetailComponent;

    public customer: ICustomer;
    public customerNote: ICustomerNote[];
    public customerNoteEntriesById: {};
    public hasSalesRights: boolean;

    constructor(public appService: AppService) {
        super();
    }

    ngOnInit() {
        this.hasSalesRights = this.appService.userHasRole(Const.USER_ROLE_SALES);
        this.customer = Factory.getEmptyCustomer();
        this.customerNote = [];
        this.customerNoteEntriesById = {};

        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 customer
     * @param isUpdate
     */
    public setData(customer: ICustomer, isUpdate: boolean): void {
        this.customer = customer;
        this.customerNote = this.customer.v_customer_notes;
        this.customerNoteEntriesById = Utils.getSortedObjFromArray(this.customerNote, 'id');
        this.modalCustomerNoteEdit.closeModal();
        this.generateEntries();
        if (isUpdate) {
            this.customerNoteDetail.updateData(customer);
        } else {
            this.modalCustomerNoteDetail.closeModal();
        }
    }

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

    /**
     * On create click
     */
    public create(): void {
        this.modalCustomerNoteEdit.openModal();
        this.customerNoteEdit.setData(this.customer, Factory.getEmptyCustomerNote(this.customer.id, Utils.getCurrentDate()), true);
    }

    /**
     * Creates customer note
     * @param customerNote
     */
    public createCustomerNoteFunction(customerNote: ICustomerNote): void {
        this.createNote.emit(customerNote);
    }

    /**
     * Edits note entry
     * @param customerNote
     */
    public editCustomerNoteFunction(customerNote: ICustomerNote) {
        this.editNote.emit(customerNote);
    }

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

}
