import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { CommonService } from '../common/common.service';

declare var SMS;

@Injectable({
    providedIn: 'root'
})
export class SmsReaderService {

    private sms: any;
    private lastCode: string;
    private features: string [] = ['hmg', 'للحبيب'];
    constructor(
        public platform: Platform,
        public cs: CommonService
    ) {
        this.sms = new SMS();
    }

    /*
  start listengin for incoming sms from hmg service
  */
    public startSMSMonitoring(onRead: any) {
        if (this.cs.isCordova()) {
            this.platform.ready().then(() => {
                this.lastCode = null;
                if (this.platform.is('android')) {
                    this.startRecieving(onRead);
                }
            });
        }
    }

    public stopSMSMonitoring() {
        if (this.cs.isCordova()) {
            this.platform.ready().then(() => {
                this.lastCode = null;
                if (this.platform.is('android')) {
                    this.sms.stopReciever();
                }
            });
        }
    }

    /*
    the sms plugin some times notify for same message many times
    */
    private startRecieving(onRead: any) {
        this.platform.ready().then(() => {
            this.platform.ready().then(() => {
                this.sms.startReciever(
                    (body: string, address) => { /* got message */

                        if (this.isTargetMessage(body)) {
                            const code = this.cs.extractNumber(body);
                            if (code && (code !== this.lastCode)) {
                                onRead(code);
                                this.lastCode = code;
                            }
                        }
                    }
                    ,
                    () => { /* reciever error*/ });
            });
        });

    }

    private isTargetMessage(body: string): boolean {
        if ( body ) {
            const lowerBody = body.toLowerCase();
            for ( const feature of this.features ){
                if ( lowerBody.indexOf(feature) >= 0 ) {
                    return true;
                }
            }
        }
        return false;
    }


}
