import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AgGridComponent} from '../../../components/ag-grid-component';
import {ModalComponent} from '../../../components/modal/modal.component';
import {OperatorContactPersonDetailComponent} from '../operator-view/operator-contact-person-detail/operator-contact-person-detail.component';
import {IOperator} from '../../../model/entities/operator';
import {OperatorService} from '../../../services/operator.service';
import {IOperatorContact} from '../../../model/entities/operator-contact';
import {Utils} from '../../../utils/utils';
import {Const} from '../../../utils/const';
import {AppService} from '../../../services/app.service';
import {CommonService} from '../../../services/common.service';

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

export class OperatorsContactListComponent extends AgGridComponent implements OnInit {

    @Output() shortcut: EventEmitter<IOperator> = new EventEmitter<IOperator>();
    @ViewChild('modalOperatorsContactPersonDetailList', { static: true }) modalOperatorsContactPersonDetailList: ModalComponent;
    @ViewChild('operatorContactPersonDetailList', { static: true }) operatorContactPersonDetailList: OperatorContactPersonDetailComponent;

    public operators: IOperator[];
    public operatorsById: {};
    private operatorContacts: IOperatorContact[];
    public operatorContactsById: {};
    public hasAdminRights: boolean;
    public hasExportRights: boolean;

    constructor(public appService: AppService, private operatorService: OperatorService, private commonService: CommonService) {
        super();
    }

    ngOnInit() {
        this.hasAdminRights = this.appService.userHasRole(Const.USER_ROLE_ADMIN);
        this.hasExportRights =
            this.appService.userHasRole(Const.USER_ROLE_ADMIN) ||
            this.appService.userHasRole(Const.USER_ROLE_TECHNIQUE);
        this.operators = [];
        this.operatorsById = {};
        this.operatorContacts = [];
        this.operatorContactsById = {};

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

        this.columnDefs = [
            {headerName: 'ID', field: 'id', width: 60 },
            {headerName: 'Betreiber ID', field: 'operator_id', width: 100 },
            {headerName: 'Betreiber', field: 'operator' },
            {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: 'Bemerkungen', field: 'comment' }
        ];

        this.rowSelection = 'single';
    }

    /**
     * Sets data
     * @param operators
     * @param operatorContacts
     */
    public setData(operators: IOperator[], operatorContacts: IOperatorContact[]): void {
        this.operators = operators;
        this.operatorsById = Utils.getSortedObjFromArray(this.operators, 'id');
        this.operatorContacts = operatorContacts;
        this.operatorContactsById = Utils.getSortedObjFromArray(this.operatorContacts, 'id');
        this.generateEntries();
    }

    /**
     * Generates AG grid entries for operators grid
     */
    public generateEntries(): void {
        this.rowData = [];

        for (let i = 0; i < this.operatorContacts.length; i++) {
            this.rowData.push({
                id: this.operatorContacts[i].id,
                operator_id: this.operatorContacts[i].operator_id,
                operator: this.operatorsById[this.operatorContacts[i].operator_id].name,
                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,
                comment: this.operatorContacts[i].comment
            });
        }
    }

    /**
     * Row is clicked
     * @param e
     */
    public rowClicked(e: any) {
        this.modalOperatorsContactPersonDetailList.openModal();
        this.operatorContactPersonDetailList.setData(this.operatorsById[e.data.operator_id], Utils.deepClone(this.operatorContactsById[e.data.id]) as IOperatorContact);
    }

    /**
     * Edit operator contact
     * @param operatorContact
     */
    public editOperatorContactFunction(operatorContact: IOperatorContact): void {
        this.operatorService.apiEditOperatorContact(operatorContact).subscribe(
            data => {
                this.operatorContactPersonDetailList.updateData(data.result_data as IOperator);
            },
            error => {}
        );
    }

    /**
     * Delete operator contact
     * @param operatorId
     */
    public deleteOperatorContactFunction(operatorId: number): void {
        this.operatorService.apiDeleteOperatorContact(operatorId).subscribe(
            data => {
                this.modalOperatorsContactPersonDetailList.closeModal();
            },
            error => {}
        );
    }

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

    /**
     * Export operator contacts pdf
     */
    public exportOperatorContactsPdf(): void {
        this.commonService.apiExportContactsPdf('Betreiber_Kontakte', 'operator');
    }

    /**
     * Export operator xmas pdf
     */
    public exportXmasPdf(): void {
        this.commonService.apiExportXmasPdf('Betreiber_Weihnachten', 'operator');
    }
}
