import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {AgGridComponent} from '../../../components/ag-grid-component';
import {ICustomer} from '../../../model/entities/customer';
import {ICustomerContact} from '../../../model/entities/customer-contact';
import {ModalComponent} from '../../../components/modal/modal.component';
import {CustomerContactPersonDetailComponent} from '../customer-view/customer-contact-person-detail/customer-contact-person-detail.component';
import {Utils} from '../../../utils/utils';
import {CustomerService} from '../../../services/customer.service';
import {isNull} from 'util';
import {Const} from '../../../utils/const';
import {AppService} from '../../../services/app.service';
import {CommonService} from '../../../services/common.service';

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

export class CustomerContactListComponent extends AgGridComponent implements OnInit {

    @Output() shortcut: EventEmitter<ICustomer> = new EventEmitter<ICustomer>();
    @ViewChild('modalCustomerContactPersonDetailList', { static: true }) modalCustomerContactPersonDetailList: ModalComponent;
    @ViewChild('customerContactPersonDetailList', { static: true }) customerContactPersonDetailList: CustomerContactPersonDetailComponent;

    public customers: ICustomer[];
    public customersById: {};
    private customerContacts: ICustomerContact[];
    public customerContactsById: {};
    public hasAdminRights: boolean;
    public hasExportRights: boolean;

    constructor(private customerService: CustomerService, private appService: AppService, private commonService: CommonService) {
        super();
    }

    ngOnInit() {
        this.hasAdminRights = this.appService.userHasRole(Const.USER_ROLE_ADMIN);
        this.hasExportRights = this.appService.userHasRole(Const.USER_ROLE_ADMIN);
        this.customers = [];
        this.customersById = {};
        this.customerContacts = [];
        this.customerContactsById = {};

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

        this.columnDefs = [
            {headerName: 'ID', field: 'id', width: 60 },
            {headerName: 'Kunden ID', field: 'customer_id', width: 100 },
            {headerName: 'Kunde', field: 'customer' },
            {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
     */
    public setData(customers: ICustomer[], customerContacts: ICustomerContact[]): void {
        this.customers = customers;
        this.customersById = Utils.getSortedObjFromArray(this.customers, 'id');
        this.customerContacts = customerContacts;
        this.customerContactsById = Utils.getSortedObjFromArray(this.customerContacts, 'id');
        this.generateEntries();
    }

    /**
     * Generates AG grid entries for customer grid
     */
    public generateEntries(): void {
        this.rowData = [];
        if (!isNull(this.customerContacts)) {
            for (let i = 0; i < this.customerContacts.length; i++) {
                this.rowData.push({
                    id: this.customerContacts[i].id,
                    customer_id: this.customerContacts[i].customer_id,
                    customer: this.customersById[this.customerContacts[i].customer_id].name,
                    firstname: this.customerContacts[i].firstname,
                    lastname: this.customerContacts[i].lastname,
                    department: this.customerContacts[i].department,
                    email: this.customerContacts[i].email,
                    phone_no: this.customerContacts[i].phone_no,
                    mobile_no: this.customerContacts[i].mobile_no,
                    fax_no: this.customerContacts[i].fax_no,
                    comment: this.customerContacts[i].comment
                });
            }
        }
    }

    /**
     * Row is clicked
     * @param e
     */
    public rowClicked(e: any) {
        this.modalCustomerContactPersonDetailList.openModal();
        this.customerContactPersonDetailList.setData(this.customersById[e.data.customer_id], Utils.deepClone(this.customerContactsById[e.data.id]) as ICustomerContact);
    }

    /**
     * Edit customer contact
     * @param customerContact
     */
    public editCustomerContactFunction(customerContact: ICustomerContact): void {
        this.customerService.apiEditCustomerContact(customerContact).subscribe(
            data => {
                this.customerContactPersonDetailList.updateData(data.result_data as ICustomer);
            },
            error => {}
        );
    }

    /**
     * Delete customer contact
     * @param contactId
     */
    public deleteCustomerContactFunction(contactId: number): void {
        this.customerService.apiDeleteCustomerContact(contactId).subscribe(
            data => {
                this.modalCustomerContactPersonDetailList.closeModal();
            },
            error => {}
        );
    }

    /**
     * Shortcut to customer detail
     * @param customer
     */
    public shortcutFunction(customer: ICustomer): void {
        this.modalCustomerContactPersonDetailList.closeModal();
        this.shortcut.emit(customer);
    }

    /**
     * Export customer contacts pdf
     */
    public exportCustomerContactsPdf(): void {
        this.commonService.apiExportContactsPdf('Kunden_Kontakte', 'customer');
    }

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