import { Injectable } from '@angular/core';
import { Observer, Observable } from 'rxjs';


@Injectable()
export class DeviceOrientationService {

  compassHeading(alpha, beta, gamma):number {

    // Convert degrees to radians
    const alphaRad = alpha * (Math.PI / 180);
    const betaRad = beta * (Math.PI / 180);
    const gammaRad = gamma * (Math.PI / 180);
  
    // Calculate equation components
    const cA = Math.cos(alphaRad);
    const sA = Math.sin(alphaRad);
    const cB = Math.cos(betaRad);
    const sB = Math.sin(betaRad);
    const cG = Math.cos(gammaRad);
    const sG = Math.sin(gammaRad);
  
    // Calculate A, B, C rotation components
    const rA = - cA * sG - sA * sB * cG;
    const rB = - sA * sG + cA * sB * cG;
    const rC = - cB * cG;
  
    // Calculate compass heading
    let compassHeading = Math.atan(rA / rB);
  
    // Convert from half unit circle to whole unit circle
    if(rB < 0) {
      compassHeading += Math.PI;
    }else if(rA < 0) {
      compassHeading += 2 * Math.PI;
    }
    return compassHeading * (180/Math.PI);
  }

  getCurrentCompassHeading(): Observable<number> {
    return Observable.create((observer: Observer<number>) => {  
        window.addEventListener("deviceorientation", (event:DeviceOrientationEvent)=>{
          const heading = this.compassHeading(event.alpha,event.beta,event.gamma);
          if(!Number.isNaN(heading)) {
            observer.next(heading);
          }
        } );
    });
  }

}
