import { Component, Input, OnInit } from '@angular/core';
import { Utils } from '@nativescript/core';
import { Observable } from 'rxjs';
import { PhoneContactService } from '~/core/services/phone-contact.service';
import { UnitContactAllOutput } from '~/pages/unit/entities/output/unitContactAllOutput';

@Component({
    moduleId: module.id,
    selector: 'UnitContacts',
    templateUrl: './unit-contacts.component.html',
    styleUrls: ['./unit-contacts.component.scss']
})
export class UnitContactsComponent implements OnInit {
    @Input() unitContacts$: Observable<UnitContactAllOutput[]>;
    @Input() isDetail: boolean;
    phone: string;
    email: string;
    web: string;

    constructor(
        private phoneContactSrv: PhoneContactService
    ) {
    }

    /**
     * In hook subscribe contacts and filter specifict contacts and save them to property
     */
    ngOnInit() {
        this.unitContacts$.subscribe(contacts => {
            contacts.forEach((contact: UnitContactAllOutput) => {
                if (contact.ID_ContactType === 'telefon_hlavni') {
                    this.phone = contact.Value;
                } else if (contact.ID_ContactType === 'email_hlavni') {
                    this.email = contact.Value;
                } else if (contact.ID_ContactType === 'web') {
                    this.web = contact.Value;
                }
            });
        });
    }

    onCreateCall(phoneNumber: string) {
        this.phoneContactSrv.createCall(phoneNumber);
    }

    async onCreateSms(phoneNumber: string) {
        try {
            await this.phoneContactSrv.createSms(phoneNumber);
        } catch (e) {
            console.error(e);
        }
    }

    async onCreateEmail(emailAddress: string) {
        try {
            await this.phoneContactSrv.createEmail(emailAddress);
        } catch (e) {
            console.error(e);
        }
    }

    onUrl(url: string) {
        Utils.openUrl(url);
    }
}
