/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { Injectable } from '@angular/core';
import { register } from 'ol/proj/proj4';
import * as proj4 from 'proj4';

@Injectable({
  providedIn: 'root',
})
export class OpenLayersProjectionsService {
  get proj4(): typeof proj4 {
    return (proj4 as any).default || proj4;
  }

  constructor() {
    register(this.proj4);
  }

  public addProjection(name: string, def: string) {
    this.proj4.defs(name, def);
    register(this.proj4);
  }

  public addProjectionLocalCartesian(name: string, centerLonLat: [number, number]) {
    const lon = centerLonLat[0];
    const lat = centerLonLat[1];
    // somehow alpha does not rotate the crs yet, but must be defined for the projection to work
    // maybe related to https://github.com/OSGeo/proj.4/commit/2cac138a22e8f01e34e9cfafb6b526694548b269,
    // but it did not seem to change anything except an anomally for >180deg
    // using 2*alpha for sin(alpha) and cos(alpha) in omerc.js worked for -90 < alpha < +90
    this.addProjection(name, `+proj=omerc +lonc=${lon} +lat_0=${lat} +alpha=0 +x_0=0 +y_0=0 +ellps=WGS84 +units=m`);
  }
}
