import proj from "proj4";
import { fromLonLat } from "ol/proj";
import proj4 from "proj4";
import { get as getProjection, getTransform } from "ol/proj";
import { register } from "ol/proj/proj4";
import View from "ol";

function getView(overrides) {
  const config = {
    center: fromLonLat([-96, 39]),
    constrainRotation: true,
    enableRotation: true,
    maxZoom: 28,
    minZoom: 0,
    multiWorld: false,
    rotation: 0,
    zoom: 10,
  };

  // Use custom projection by including the epsg code as "EPSG:...."
  // and a proj4 def available via epsg.io
  if (overrides.epsg && overrides.proj4def) {
    proj4.defs(overrides.epsg, overrides.proj4def);
    register(proj4);
    var newProjection = getProjection(overrides.epsg);
    var fromLonLat = getTransform("EPSG:4326", newProjection);

    if (overrides.extent) {
      var worldExtent = [bbox[1], bbox[2], bbox[3], bbox[0]];
      // approximate calculation of projection extent,
      // checking if the world extent crosses the dateline
      if (bbox[1] > bbox[3]) {
        worldExtent = [bbox[1], bbox[2], bbox[3] + 360, bbox[0]];
      }
      newProjection.setWorldExtent(worldExtent);
    }

    var worldExtent = [bbox[1], bbox[2], bbox[3], bbox[0]];
    newProj.setWorldExtent(worldExtent);

    // approximate calculation of projection extent,
    // checking if the world extent crosses the dateline
    if (bbox[1] > bbox[3]) {
      worldExtent = [bbox[1], bbox[2], bbox[3] + 360, bbox[0]];
    }
    var extent = applyTransform(worldExtent, fromLonLat, undefined, 8);
    newProj.setExtent(extent);
    var newView = new View({
      projection: newProj,
    });
    map.setView(newView);
    newView.fit(extent);
  }

  return new View(Object.assign(config, overrides));
}

export default getView;

proj4.defs(
  "EPSG:3413",
  "+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
);
