import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AgGridComponent} from '../../../../components/ag-grid-component';
import {ModalComponent} from '../../../../components/modal/modal.component';
import {IConfig} from '../../../../model/virtual/config';
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 {IOperatorContact} from '../../../../model/entities/operator-contact';
import {OperatorContactPersonDetailComponent} from '../operator-contact-person-detail/operator-contact-person-detail.component';
import {OperatorContactPersonEditComponent} from '../operator-contact-person-edit/operator-contact-person-edit.component';
import {IOperator} from '../../../../model/entities/operator';

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

export class OperatorContactPersonViewComponent extends AgGridComponent implements OnInit {

    @Output() createOperatorContact: EventEmitter<IOperatorContact> = new EventEmitter<IOperatorContact>();
    @Output() editOperatorContact: EventEmitter<IOperatorContact> = new EventEmitter<IOperatorContact>();
    @Output() deleteOperatorContact: EventEmitter<number> = new EventEmitter<number>();
    @Output() shortcut: EventEmitter<IOperator> = new EventEmitter<IOperator>();
    @ViewChild('modalOperatorContactPersonEdit', { static: true }) modalOperatorContactPersonEdit: ModalComponent;
    @ViewChild('operatorContactPersonEdit', { static: true }) operatorContactPersonEdit: OperatorContactPersonEditComponent;
    @ViewChild('modalOperatorContactPersonDetail', { static: true }) modalOperatorContactPersonDetail: ModalComponent;
    @ViewChild('operatorContactPersonDetail', { static: true }) operatorContactPersonDetail: OperatorContactPersonDetailComponent;

    public operator: IOperator;
    public operatorContacts: IOperatorContact[];
    public operatorContactsById: {};
    public config: IConfig;
    public hasEditRights: boolean;

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

    ngOnInit() {
        this.hasEditRights =
            this.appService.userHasRole(Const.USER_ROLE_TECHNIQUE) ||
            this.appService.userHasRole(Const.USER_ROLE_ACCOUNTING);
        this.config = this.appService.getConfig();
        this.operator = Factory.getEmptyOperator();
        this.operatorContacts = [];
        this.operatorContactsById = {};

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

        this.columnDefs = [
            {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' },
            {headerName: 'Straße', field: 'street' },
            {headerName: 'Hausnummer', field: 'street_no' },
            {headerName: 'PLZ', field: 'zip' },
            {headerName: 'Ort', field: 'city' },
            {headerName: 'Land', field: 'country' },
            {headerName: 'Bemerkungen', field: 'comment' }
        ];
    }

    /**
     * Sets data
     * @param operator
     * @param isUpdate
     */
    public setData(operator: IOperator, isUpdate: boolean): void {
        this.operator = operator;
        this.operatorContacts = this.operator.v_operator_contacts;
        this.operatorContactsById = Utils.getSortedObjFromArray(this.operatorContacts, 'id');
        this.modalOperatorContactPersonEdit.closeModal();
        this.generateEntries();
        if (isUpdate) {
            this.operatorContactPersonDetail.updateData(operator);
        } else {
            this.modalOperatorContactPersonDetail.closeModal();
        }
    }

    /**
     * Generates AG grid entries
     */
    public generateEntries(): void {
        this.rowData = [];
        for (let i = 0; i < this.operatorContacts.length; i++) {
            let ocGender: string;
            if (this.operatorContacts[i].gender == 'male') {
                ocGender = 'Herr';
            } else if (this.operatorContacts[i].gender == 'female') {
                ocGender = 'Frau';
            } else {
                ocGender = 'Divers';
            }
            this.rowData.push({
                id: this.operatorContacts[i].id,
                gender: ocGender,
                firstname: this.operatorContacts[i].firstname,
                lastname: this.operatorContacts[i].lastname,
                department: this.operatorContacts[i].department,
                email: this.operatorContacts[i].email,
                phone_no: this.operatorContacts[i].phone_no,
                mobile_no: this.operatorContacts[i].mobile_no,
                fax_no: this.operatorContacts[i].fax_no,
                street: this.operatorContacts[i].street,
                street_no: this.operatorContacts[i].street_no,
                zip: this.operatorContacts[i].zip,
                city: this.operatorContacts[i].city,
                country: !isNull(this.operatorContacts[i].country_id) ? this.config.vc_countries_by_id[this.operatorContacts[i].country_id].name : null,
                comment: this.operatorContacts[i].comment,
            });
        }
    }

    /**
     * On row click
     * @param e
     */
    public rowClicked(e: any) {
        this.modalOperatorContactPersonDetail.openModal();
        this.operatorContactPersonDetail.setData(this.operator, Utils.deepClone(this.operatorContactsById[e.data.id]) as IOperatorContact);
    }

    /**
     * On create click
     */
    public create(): void {
        this.modalOperatorContactPersonEdit.openModal();
        this.operatorContactPersonEdit.setData(Factory.getEmptyOperatorContact(this.operator.id));
    }

    /**
     * Creates operator contact
     * @param operatorContact
     */
    public createOperatorContactFunction(operatorContact: IOperatorContact): void {
        this.createOperatorContact.emit(operatorContact);
    }

    /**
     * Edit operator contact
     * @param operatorContact
     */
    public editOperatorContactFunction(operatorContact: IOperatorContact): void {
        this.editOperatorContact.emit(operatorContact);
    }

    /**
     * Deletes operator contact
     * @param operatorId
     */
    public deleteOperatorContactFunction(operatorId: number): void {
        this.deleteOperatorContact.emit(operatorId);
    }

    /**
     * Shortcut to operator detail
     * @param operator
     */
    public shortcutFunction(operator: IOperator): void {
        this.modalOperatorContactPersonDetail.closeModal();
        this.shortcut.emit(operator);
    }

}
