import { Component, Input, OnInit } from '@angular/core';
import { ImageSource, isAndroid } from '@nativescript/core';
import { Observable } from 'rxjs';
import { PhoneContactService } from '~/core/services/phone-contact.service';
import { PersonContactAllOutput } from '~/pages/search-person/entities/output/personContactAllOutput';
import { PersonDetailOutput } from '~/pages/search-person/entities/output/personDetailOutput';
import { PersonPhotoOutput } from '~/pages/search-person/entities/output/personPhotoOutput';

@Component({
    selector: 'SearchPersonDetailHeader',
    moduleId: module.id,
    templateUrl: './search-person-detail-header.component.html',
    styleUrls: ['./_search-person-detail-header.component.scss']
})
export class SearchPersonDetailHeaderComponent implements OnInit {
    @Input() personDetail: PersonDetailOutput;
    @Input() personPhoto$: Observable<PersonPhotoOutput>;
    @Input() personContacts$: Observable<PersonContactAllOutput[]>;
    personPhotoResource;
    phoneMain: PersonContactAllOutput;
    emailMain: PersonContactAllOutput;
    isAndroidDevice = isAndroid;

    constructor(
        private phoneContactSrv: PhoneContactService
    ) {
    }

    /**
     * In OnInit hook I subscribe data.
     *
     * PersonPhoto subscribed data I transform to ImageSource and
     * personContacts subscribed data I use for finding phone and email
     *
     */
    ngOnInit(): void {
        this.personPhoto$.subscribe(
            personPhoto => {
                if (personPhoto) {
                    this.personPhotoResource = ImageSource.fromBase64Sync(personPhoto.PhotoContent);
                }
            }
        );
        this.personContacts$.subscribe(
            personContacts => {
                this.phoneMain = personContacts.find(c => c.ID_ContactType === 'telefon_hlavni');
                this.emailMain = personContacts.find(c => c.ID_ContactType === 'email_hlavni');

            }
        );
    }

    get personPhone() {
        return this.personDetail.Phone || (this.phoneMain && this.phoneMain.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);
        }
    }

    get personEmail() {
        return this.personDetail.Email || (this.emailMain && this.emailMain.Value);
    }

    onAddContact() {
        this.phoneContactSrv.addPersonContact(this.personEmail, this.personPhone, this.personDetail.FirstName, this.personDetail.LastName, this.personDetail.DisplayName, this.personPhotoResource);
    }
}
