import GeoJSON from 'ol/format/GeoJSON';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Fill from 'ol/style/Fill';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import Text from 'ol/style/Text';

export const OL_PROJECTION = 'EPSG:3857';

export const createGeoJSONLayer = (options: any) => {
  const { data, style = null, popupProperties = null } = options;

  const source =
    typeof data === 'string'
      ? new VectorSource({
          url: data,
          format: new GeoJSON(),
        })
      : new VectorSource({
          features: new GeoJSON().readFeatures(data, {
            dataProjection: 'EPSG:4326', // projection của dữ liệu
            featureProjection: 'EPSG:3857', // projection bản đồ
          }),
        });

  return new VectorLayer({
    source,
    style: style,
    properties: {
      popupProperties,
    },
  });
};

const createLabelStyle = (feature: any) => {
  const tenTinh = feature.get('tenTinh');
  return new Style({
    stroke: new Stroke({
      color: '#333',
      width: 1,
    }),
    fill: new Fill({
      color: 'rgba(0, 150, 255, 0.2)',
    }),
    text: new Text({
      font: '14px Calibri,sans-serif',
      fill: new Fill({ color: '#000' }),
      stroke: new Stroke({ color: '#fff', width: 3 }),
      text: tenTinh || '',
    }),
  });
};

export const createLabelAndFillStyle = (
  fillColor = 'rgba(255,0,0,0.1)',
  strokeColor = '#ff0000',
) => {
  return (feature: any) => {
    const tenTinh = feature.get('tenTinh');

    return new Style({
      stroke: new Stroke({ color: strokeColor, width: 1 }),
      fill: new Fill({ color: fillColor }),
      text: new Text({
        font: '14px Calibri,sans-serif',
        fill: new Fill({ color: '#000' }),
        stroke: new Stroke({ color: '#fff', width: 3 }),
        text: tenTinh || '',
      }),
    });
  };
};
