import { Injectable } from '@angular/core';
import { Application, isAndroid } from '@nativescript/core';
// import * as contacts from 'nativescript-contacts';
import * as email from 'nativescript-email';
import { Feedback, FeedbackType } from 'nativescript-feedback';
// import * as Permissions from 'nativescript-permissions';
import * as phone from 'nativescript-phone';

declare var android: any;

/**
 * Service takes care of creating call, sms, email or adding contact to contact list in phone
 */
@Injectable()
export class PhoneContactService {
    /**
     * It open window for dialing number with pre-filled phone number
     *
     * @param {string} phoneNumber
     * @return {void}
     */
    createCall(phoneNumber: string): void {
        phone.dial(phoneNumber, true);
    }

    /**
     * It open window for write sms with pre-filled phone number
     * @param {string} phoneNumber
     * @return {Promise<void>}
     */
    async createSms(phoneNumber: string): Promise<void> {
        try {
            await phone.sms([phoneNumber], '');
        } catch (e) {
            console.error(e);
        }
    }

    /**
     * It open app for send email with pre-filled email address
     *
     * @param {string} emailAddress
     * @return {Promise<void>}
     */
    async createEmail(emailAddress: string, subject: string = ''): Promise<void> {
        const composeOptions: email.ComposeOptions = {
            to: [emailAddress], subject
        };
        try {
            const available = await email.available();
            if (available) {
                await email.compose(composeOptions);
            } else {
                console.log('Email service is not available');
            }
        } catch (e) {
            console.error(e);
        }
    }

    /**
     * It add person with contacts to contact list
     *
     * @param {string} emailAddress
     * @param {string} phoneNumber
     * @param {string} firstName
     * @param {string} lastName
     * @param {string} displayName
     * @return {void}
     */
    addPersonContact(emailAddress: string, phoneNumber: string, firstName: string, lastName: string, displayName: string, personPhotoResource: any): void {
        const feedback = new Feedback();
        // use android native code due to bug in nativescript-contacts : https://github.com/firescript/nativescript-contacts/issues/76
        if (isAndroid) {
            try {
                const intent = new android.content.Intent(android.provider.ContactsContract.Intents.Insert.ACTION);
                intent.setType(android.provider.ContactsContract.RawContacts.CONTENT_TYPE);
                intent
                    .putExtra(android.provider.ContactsContract.Intents.Insert.EMAIL, emailAddress)
                    .putExtra(android.provider.ContactsContract.Intents.Insert.EMAIL_TYPE, android.provider.ContactsContract.CommonDataKinds.Email.TYPE_OTHER)
                    .putExtra(android.provider.ContactsContract.Intents.Insert.PHONE, phoneNumber)
                    .putExtra(android.provider.ContactsContract.Intents.Insert.PHONE_TYPE, android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_OTHER)
                    .putExtra(android.provider.ContactsContract.Intents.Insert.NAME, firstName + ' ' + lastName);

                Application.android.foregroundActivity.startActivity(intent);
            } catch (e) {
                feedback.show({
                    title: 'Error',
                    type: FeedbackType.Error,
                    message: e.message
                });
            }

        }
        // const newContact = new contacts.Contact();
        // newContact.name.given = firstName;
        // newContact.name.family = lastName;
        // newContact.name.displayname = displayName;
        // newContact.phoneNumbers.push({ label: contacts.KnownLabel.OTHER, value: phoneNumber });
        // newContact.emailAddresses.push({ label: contacts.KnownLabel.OTHER, value: emailAddress });
        // newContact.photo = personPhotoResource;
        // Permissions.requestPermissions([android.Manifest.permission.GET_ACCOUNTS, android.Manifest.permission.WRITE_CONTACTS], 'Tato oprávněné jsou nezbytná pro ukládání kontaktu do telefonu.')
        //     .then(() => {
        //         // newContact.save();
        //         feedback.show({
        //             title: 'Success',
        //             type: FeedbackType.Success,
        //             message: 'Kontakt byl přidán do seznamu kontaktů.'
        //         });
        //     })
        //     .catch(e => {
        //         feedback.show({
        //             title: 'Warning',
        //             type: FeedbackType.Warning,
        //             message: 'Nepodařilo se přidat kontakt do seznamu kontaktů.'
        //         });
        //         console.error(e);
        //     });
    }
}
