import { polygonOptions } from './config';
import * as L from 'leaflet';
import {cloneDeep} from 'lodash';

export function formatPath(oldPath) {
  let path = cloneDeep(oldPath)
  let pathArr = [];
  if (!path) {
    return pathArr;
  }
  if (typeof path === 'string') {
    try {
      if(Array.isArray(JSON.parse(oldPath))){
        pathArr=JSON.parse(oldPath)
      }else{
        pathArr = path.split('|').map((path2) => path2.split(';').map((v) => new L.latLng(...v.split(',').reverse())));
      }
    } catch (error) {
      pathArr = path.split('|').map((path2) => path2.split(';').map((v) => new L.latLng(...v.split(',').reverse())));

    }
  }
  if (Array.isArray(path)) {
    pathArr = path;
  }
  return pathArr;
}
export function ArrayPath(oldPath) {
  let path = cloneDeep(oldPath)
  let pathArr = [];
  if (path && Array.isArray(path)) {
    pathArr = path.map(v => new L.latLng(v.reverse()));
  }
  return pathArr;
}
function eventTarget(e, { fillOpacity }) {
  e.target.setStyle({ fillOpacity });
}

export function createPolygon(oldPath, options = {}, boundsReact) {
  let path = cloneDeep(oldPath)
  let pathArr = [];
  if (path && typeof path === 'string') {
    pathArr = formatPath(path);
  } else {
    pathArr = ArrayPath(path);
  }
  return L.polygon(boundsReact ? [boundsReact, pathArr] : pathArr, { ...polygonOptions, dashArray: 10, ...options })
    .on('mouseover', (e) => eventTarget(e, { fillOpacity: 0.3 }))
    .on('mouseout', (e) => eventTarget(e, { fillOpacity: 0.1 }));
}
