import dayjs from "dayjs";
import "dayjs/locale/cs";
import type { ExtendedPageProps } from "../types";
import { usePage } from '@inertiajs/vue3'
import { trans } from "craftable-pro/plugins/laravel-vue-i18n";

const page = usePage<ExtendedPageProps>();

export const getDateRange = (dateFrom: string | undefined, dateTo: string | undefined, format: string, lang: string) => {
  if (!dateFrom || dateFrom === undefined || dateFrom === "") return "";

  const _dateFrom = dayjs(dateFrom).locale(lang);
  const _dateTo = dayjs(dateTo).locale(lang);

  return _dateFrom.month() == _dateTo.month() && _dateFrom.year() == _dateTo.year()
    ? _dateFrom.format(format) : _dateFrom.format(format) + " - " + _dateTo.format(format);
};

export const getYear = (date: string) => {
  return dayjs(date).year();
}

export const isEmpty = (value: string | undefined) => {
  return !value || value === undefined || value === "";
};

export const controlButtonStyles = (controlButton: HTMLButtonElement) => {
  // Set CSS for the control.

  controlButton.classList.add('bg-white','rounded-sm', 'shadow', 'pointer', 'text-neutral-900', 'text-base', 'w-10', 'h-10', 'mt-2', 'text-center', 'group')
  controlButton.style.border = '2px solid #fff';
  controlButton.style.padding = '0 6px';
  controlButton.style.marginRight = '10px';
};

export const controlGroupButtonStyles = (controlButton: HTMLButtonElement) => {
  // Set CSS for the control.

  controlButton.classList.add('bg-white', 'first:rounded-t-sm', 'last:rounded-b-sm', 'shadow', 'pointer', 'text-neutral-900', 'text-base', 'w-10', 'h-10', 'text-center', 'group')
  controlButton.style.border = '2px solid #fff';
  controlButton.style.padding = '0 6px';
  controlButton.style.marginRight = '10px';
};

export const tooltipHTML = (label: string) => {
  return '<span class="tooltip rounded shadow-lg py-1 px-3 bg-white text-neutral-900 top-[3px] bottom-auto right-[128%] w-max">' + label + '</span>';
}

export const mapStyles = [
  {
    "elementType": "labels",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "administrative",
    "elementType": "geometry",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "poi",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "road",
    "elementType": "labels.icon",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "road.local",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  },
  {
    "featureType": "transit",
    "stylers": [
      {
        "visibility": "off"
      }
    ]
  }
];

export const convertTileCoordsToLatLng = (tileCoords: google.maps.Point, map: any, tileSize: number, scale: number): google.maps.LatLng => {
  const projection = map.getProjection();
  const pixelCoords = new google.maps.Point((tileCoords.x) * tileSize, (tileCoords.y) * tileSize);
  const worldCoords = new google.maps.Point ( (pixelCoords.x) / scale, (pixelCoords.y) / scale);
  return projection.fromPointToLatLng (worldCoords);
}

const xyzToBounds = (x: number, y: number, zoom: number) => {
  const EPSG_3857_EXTENT = 20037508.34789244;
  const ORIG_X = -EPSG_3857_EXTENT;
  const ORIG_Y = EPSG_3857_EXTENT;

  const tileSize = (EPSG_3857_EXTENT * 2) / Math.pow(2, zoom);

  const minx = ORIG_X + x * tileSize;
  const maxx = ORIG_X + (x + 1) * tileSize;

  const miny = ORIG_Y - (y + 1) * tileSize;
  const maxy = ORIG_Y - y * tileSize;

  const left = minx;
  const bottom = miny;
  const right = maxx;
  const top = maxy;

  return [left, bottom, right, top,].join(",");
}

export const getTileUrlForWms = (url: string, layer_id: string, coord: any, zoom: any, tile_size: number): string => {
  const bbox = xyzToBounds (coord.x, coord.y, zoom);

  const queryString = new URLSearchParams();
  queryString.set("layers", layer_id);
  queryString.set("bbox", bbox);
  queryString.set("styles", "");
  queryString.set("bgcolor", "0xFFFFFF");
  queryString.set("outline", "false");
  queryString.set("transparent", "true");
  queryString.set("format", "image/png");
  queryString.set("width", String(tile_size));
  queryString.set("height", String(tile_size));
  queryString.set("version", "1.1.1");
  queryString.set("request", "GetMap");
  queryString.set("service", "WMS");
  queryString.set("srs", "EPSG:3857");

  let resultUrl = url;

  if (!url.endsWith("?")) {
    resultUrl += "?";
  }

  return resultUrl + queryString.toString();
}

export const getMeasurementText = (mode: string): string => {
  switch (mode) {
    case "line":
      return trans("craftable-pro", "measurement_text_line");
    case "polyline":
      return trans("craftable-pro", "measurement_text_polyline");
    case "polygon":
      return trans("craftable-pro", "measurement_text_polygon");
    case "point":
      return trans("craftable-pro", "measurement_text_point");
    default:
      return "";
  }
}

export const formatLength = (number: number): string => {
  if (number < 0.01) {
    return (number * 1000).toFixed(3) + " mm";
  } else if (number < 1) {
    return (number * 100).toFixed(3) + " cm";
  } else if (number < 1000) {
    return number.toFixed(3) + " m";
  } else {
    return (number / 1000).toFixed(3) + " km"
  }
}

export const formatArea = (number: number): string => {
  if (number < 1000000) {
    return number.toFixed(3) + " m2"
  } else {
    return (number / (1000**2)).toFixed(3) + " km2"
  }
}

export const markerInput = (label: string, text: string, isFirst: boolean): string => {
  return '<div class="mt-2"><div class="pb-1">' + label + '</div><div class="relative flex rounded-md shadow-sm">'
    + '<div class="relative w-full">'
    + '<input type="text" readonly value="' + text + '" class="border-gray-300 focus:border-primary-500 focus:ring-primary-500 block w-60 rounded-md text-sm text-gray-800 focus:outline-none rounded-l-none rounded-r-none py-1.5 px-3" />'
    + '</div>'
    + '<span class="inline-flex items-center rounded-r-md border border-l-0 border-gray-300 text-gray-500 sm:text-sm">'
    + '<button type="button" title="' + trans("craftable-pro", "measurement_copy_to_clipboard_button_title") + '" data-value="' + text + '" class="copy-to-clipboard text-primary-500 hover:bg-primary-500 hover:text-white focus:ring-4 focus:outline-none focus:ring-primary-500 font-medium text-sm p-1 text-center inline-flex items-center me-2">'
    + '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">'
    + '<path stroke-linecap="round" stroke-linejoin="round" d="M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 01-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 011.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 00-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 01-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 00-3.375-3.375h-1.5a1.125 1.125 0 01-1.125-1.125v-1.5a3.375 3.375 0 00-3.375-3.375H9.75" />'
    + '</svg><span class="sr-only">Copy to clipboard</span>'
    + '</button></span>'
    + '</div></div>';
}

export const storageAvailable = (type: string): boolean => {
  let storage;
  try {
    storage = window[type];
    const x = "__storage_test__";
    storage.setItem(x, x);
    storage.removeItem(x);
    return true;
  } catch (e) {
    return false;
  }
}

export const newSvgShape = (item: SvgRectShape|null, link?: string, title?: string) => {
  return {
    type: item ? item.type : 'rect',
    active: false,
    x: item ? item.x : 30,
    y: item ? item.y : 30,
    width: item ? item.width : 100,
    height: item ? item.height : 50,
    drag: {
      type: '',
      x: 0,
      y: 0,
      mx: 0,
      my: 0,
      w: 0,
      h: 0,
      handleID: ''
    },
    text: item ? item.text : '___',
    fontSize: item ? item.fontSize : 32,
    link: link ?? '',
    title: title ?? '',
  }
}

export const loadOrderingSettings = (orderingSettings: string, options: Array<string>): {sortKey: string, reverse: boolean} => {
  if (!orderingSettings || orderingSettings.split(';').length != 2) {
    return {
      sortKey: '',
      reverse: false,
    }
  }

  let settings = orderingSettings.split(';')
  if (!options.includes(settings[0])) {
    return {
      sortKey: '',
      reverse: false,
    }
  }

  return {
    sortKey: settings[0],
    reverse: settings[1]  == 'true',
  }
}

export const getCustomLabelWithLocale = (label: string,  locale: string) => {
  return `[${locale.toUpperCase()}] ${label}`;
};
