//import WMTSTileGrid from 'ol/tilegrid/WMTS';
import proj4 from 'proj4';
import {Fill, Stroke, Style} from 'ol/style';
import {OSM, TileWMS, Vector as VectorSource, XYZ, WMTS} from 'ol/source';
import {Tile, Vector as VectorLayer} from 'ol/layer';
import {TopoJSON} from 'ol/format';
import {View} from 'ol';
import {get as getProjection, transform} from 'ol/proj';
//import {getTopLeft, getWidth} from 'ol/extent';
import {register} from 'ol/proj/proj4';

import env from './env.config.json';
import i18n from './translations.json';

proj4.defs(
  'EPSG:3045',
  '+proj=utm +zone=33 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs'
);
proj4.defs(
  'EPSG:5514',
  '+proj=krovak +lat_0=49.5 +lon_0=24.83333333333333 +alpha=30.28813972222222 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel +towgs84=542.5,89.2,456.9,5.517,2.275,5.516,6.96 +units=m +no_defs'
);
register(proj4);
const sjtskProjection = getProjection('EPSG:5514');
//const utm33nProjection = getProjection('EPSG:3045');

function getHostname() {
  const url = window.location.href;
  const urlArr = url.split('/');
  const domain = urlArr[2];
  return urlArr[0] + '//' + domain;
}

export const cartodbLayer = new Tile({
  properties: {
    title: 'OpenStreetMap světlá',
    base: true,
    editor: {editable: false},
    removable: false,
  },
  source: new XYZ({
    url:
      'https://cartodb-basemaps-{a-d}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',
    attributions: [
      'CartoDB Positron, © <a href="https://carto.com/attributions" target="_blank">CARTO</a>',
      '© <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors',
    ],
  }),
  visible: true,
});

export const osmLayer = new Tile({
  properties: {
    title: 'OpenStreetMap barevná',
    base: true,
    editor: {editable: false},
    removable: false,
  },
  source: new OSM(),
  visible: false,
});

export const zm100Layer = new Tile({
  properties: {
    title: 'Mapa ČR 1:100 000',
    base: true,
    removable: false,
  },
  source: new TileWMS({
    url: 'https://geoportal.cuzk.cz/WMS_ZM100_PUB/WMService.aspx',
    params: {
      LAYERS: 'GR_ZM100',
    },
    attributions: ['© <a href="geoportal.cuzk.cz" target="_blank">ČÚZK</a>'],
  }),
  /*source: new TileWMS({
    url:
      'https://ags.cuzk.cz/arcgis/services/VektorovaMapa/MapServer/WmsServer?',
    params: {
      //https://ags.cuzk.cz/arcgis/services/VektorovaMapa/MapServer/WmsServer?request=GetCapabilities&service=WMS
      LAYERS: `1,2,3,4,5,6,7,8,9,10,11,12,13,14,193,194,195,196,
17,18,15,16,82,83,84,85,86,87,88,89,90,91,182,183,184,185,186,187,188,189,190,191,192,
19,20,78,79,80,81,23,24,21,22,197,198,199,200,201,202,203,204,205,
52,53,54,
26,27,92,94,93,95,96,
29,30,31,32,76,97,98,99,100,101,102,103,104,108,109,105,106,107,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155`,
    },
  }),*/
  /*source: new WMTS({
    url: 'https://geoportal.cuzk.cz/WMTS_ZM/WMTService.aspx',
    format: 'image/png',
    layer: 'zm',
    matrixSet: 'jtsk:epsg:5514',
    tileGrid: new WMTSTileGrid({
      origin: [51.874963785131, 11.082166373399],
      resolutions: [
        3,2,1
      ],
      matrixIds: [1, 2, 3],
    }),
  }),*/
  visible: false,
});

export const mcr500Layer = new Tile({
  properties: {
    title: 'Mapa ČR 1:500 000',
    base: true,
    removable: false,
  },
  source: new TileWMS({
    url: 'https://geoportal.cuzk.cz/WMS_MCR500/WMService.aspx',
    params: {
      LAYERS: 'GR_MCR500',
    },
    attributions: ['© <a href="geoportal.cuzk.cz" target="_blank">ČÚZK</a>'],
  }),
  
  visible: false,
});

export const ortofotoLayer = new Tile({
  properties: {
    title: 'Ortofoto ČÚZK',
    base: true,
    removable: false,
    thumbnail: 'https://www.agrihub.sk/hsl-ng/img/orto.jpg',
  },
  source: new TileWMS({
    url: 'https://geoportal.cuzk.cz/WMS_ORTOFOTO_PUB/WMService.aspx',
    params: {
      LAYERS: 'GR_ORTFOTORGB',
    },
    attributions: ['© <a href="geoportal.cuzk.cz" target="_blank">ČÚZK</a>'],
  }),
  visible: false,
});

export const perc2color = (perc: number): string => {
  perc = perc * 100;
  let r;
  let g;
  const b = 0;
  if (perc < 50) {
    r = 255;
    g = Math.round(5.1 * perc);
  } else {
    g = 255;
    r = Math.round(510 - 5.1 * perc);
  }
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const h = r * 0x10000 + g * 0x100 + b * 0x1;
  return `rgba(${r}, ${g}, ${b}, 0.7)`;
};

const decimal2prettyPerc = (x) => {
  return `${(x * 100).toFixed(2)}&nbsp;%`;
};

const indexStyle = (feature) => {
  if (isNaN(feature.get('aggregate'))) {
    return [
      new Style({
        fill: new Fill({
          color: '#FFF',
        }),
        stroke: new Stroke({
          color: '#3399CC',
          width: 0.25,
        }),
      }),
    ];
  } else {
    return [
      new Style({
        fill: new Fill({
          color: perc2color(feature.get('aggregate')),
        }),
        stroke: new Stroke({
          color: '#FFFFFF',
          width: 0.15,
        }),
      }),
    ];
  }
};

export const obce = new VectorSource({
  format: new TopoJSON({dataProjection: 'EPSG:5514'}),
  url: require('./data/obce_cr_20210310_5p_5514.topojson').default,
  overlaps: false,
  attributions: ['CC-BY ČÚZK, 2021'],
});

export const obceIndexLayer = new VectorLayer({
  properties: {
    editor: {editable: false},
    autoLegend: false,
    title: 'Obce ČR: Rural attractiveness index',
  },
  source: obce,
  visible: true,
  style: indexStyle,
});
obceIndexLayer.set('popUp', {
  attributes: [
    {
      attribute: 'aggregate',
      label: 'agregovaný index',
      displayFunction: decimal2prettyPerc,
    },
    {
      attribute: 'Konec chudoby',
      displayFunction: decimal2prettyPerc,
    },
    {
      attribute: 'Zdraví a kvalitní život',
      displayFunction: decimal2prettyPerc,
    },
    {
      attribute: 'Kvalitní vzdělání',
      displayFunction: decimal2prettyPerc,
    },
    {
      attribute: 'Důstojná práce a ekonomický růst',
      displayFunction: decimal2prettyPerc,
    },
    {
      attribute: 'Udržitelná města a obce',
      displayFunction: decimal2prettyPerc,
    },
    {
      attribute: 'Ostatní',
      displayFunction: decimal2prettyPerc,
    },
  ],
});
obceIndexLayer.set('editable', false);
//obceIndexLayer.set('queryable', false);

const masStyle = (feature) =>
  new Style({
    fill: new Fill({
      color: feature.get('mas_type') == 'member' ? '#1d941d' : '#f6cd61',
    }),
    stroke: new Stroke({
      color: '#ffffff',
      width: 0.6,
    }),
  });

export const masLayer = new VectorLayer({
  properties: {
    editor: {editable: false},
    title: 'MAS ČR',
    attributions: ['&copy; NS MAS ČR, http://nsmascr.cz/o-nas/'],
    popUp: {
      attributes: [
        /*{attribute: 'mas_type', label: 'člen NS MAS?', displayFunction: (attr) => {TODO:}}*/
      ],
    },
  },
  source: new VectorSource({
    format: new TopoJSON({dataProjection: 'EPSG:5514'}),
    url: require('./data/mas_2021.topojson').default,
    overlaps: false,
  }),
  visible: false,
  opacity: 0.8,
  style: masStyle,
});

const okresyStyle = new Style({
  stroke: new Stroke({
    color: '#111111',
    width: 0.4,
  }),
});

export const okresyLayer = new VectorLayer({
  properties: {
    editor: {editable: false},
    title: 'Okresy ČR',
    attributions: ['CC-BY ČÚZK, 2021'],
  },
  source: new VectorSource({
    format: new TopoJSON({dataProjection: 'EPSG:5514'}),
    url: require('./data/okresy_cr_20210310_5p_5514.topojson').default,
    overlaps: false,
  }),
  visible: false,
  style: okresyStyle,
});

const krajeStyle = new Style({
  stroke: new Stroke({
    color: '#000000',
    width: 0.6,
  }),
});

export const krajeLayer = new VectorLayer({
  properties: {
    editor: {editable: false},
    title: 'Kraje ČR',
    attributions: ['CC-BY ČÚZK, 2021'],
  },
  source: new VectorSource({
    format: new TopoJSON({dataProjection: 'EPSG:5514'}),
    url: require('./data/kraje_cr_20210310_5p_5514.topojson').default,
    overlaps: false,
  }),
  visible: true,
  style: krajeStyle,
});

export const AppConfig = {
  assetsPath: 'assets/hslayers-ng',
  useProxy: false,
  //proxyPrefix: '../8085/',
  geonamesUser: env.geonamesUser,
  default_layers: [cartodbLayer, osmLayer, mcr500Layer, ortofotoLayer],
  popUpDisplay: 'hover',
  project_name: 'erra/map',
  default_view: new View({
    projection: sjtskProjection,
    center: transform([15.628, 49.864249], 'EPSG:4326', 'EPSG:5514'),
    zoom: 7.6,
  }),
  advanced_form: true,
  datasources: [],
  hostname: {
    default: {
      title: 'Default',
      type: 'default',
      editable: false,
      url: getHostname(),
    },
  },
  panelWidths: {
    datasource_selector: 400,
  },
  panelsEnabled: {
    composition_browser: false,
    feature_crossfilter: false,
    info: true,
    saveMap: false,
    sensors: false,
    tracking: false,
    routing: false,
    permalink: false,
    legend: false,
    feature_table: false,
    draw: false,
  },
  status_manager_url: '/statusmanager/',
  sidebarPosition: 'right',
  sizeMode: 'fullscreen',
  translationOverrides: i18n,
};

export default AppConfig;
