import "core-js/modules/es.array.iterator";
import "core-js/modules/web.dom-collections.iterator";
import _JSON$stringify from "@babel/runtime-corejs3/core-js-stable/json/stringify";
import _findInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _Object$assign from "@babel/runtime-corejs3/core-js-stable/object/assign";
import _setTimeout from "@babel/runtime-corejs3/core-js-stable/set-timeout";
import _Array$isArray from "@babel/runtime-corejs3/core-js-stable/array/is-array";
import _Object$keys from "@babel/runtime-corejs3/core-js-stable/object/keys";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _objectWithoutPropertiesLoose from "@babel/runtime-corejs3/helpers/objectWithoutPropertiesLoose";
// @flow
import React, { useState, useLayoutEffect, useMemo } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import ReportViewContent from './ReportViewContent';
/*:: import { type ReportViewContentProps } from './ReportViewContent';*/

import ViewWrapper from '../ViewWrapper';
/*:: import { type CommonViewProps } from '../ViewWrapper';*/

import Toolbar from '../internal/Toolbar';
import PrintButton from './PrintButton';
import HideFieldsButton from './HideFieldsButton';
import { fieldKeyToLabel } from '../utils/strings';
import getStats from '../stats';
/*:: import type { Observation } from 'mapeo-schema'*/

/*:: import type { PresetWithAdditionalFields, FieldState, Field } from '../types'*/

/*:: type Props = {
  ...$Exact<CommonViewProps>,
  ...$Exact<ReportViewContentProps>
}*/

const hiddenTags = {
  categoryId: true,
  notes: true,
  note: true
};

const ReportView = (_ref) => {
  let {
    observations,
    onUpdateObservation,
    onDeleteObservation,
    presets,
    filter,
    getMediaUrl
  }
  /*: Props*/
  = _ref,
      otherProps = _objectWithoutPropertiesLoose(_ref, ["observations", "onUpdateObservation", "onDeleteObservation", "presets", "filter", "getMediaUrl"]);

  const stats = useMemo(() => getStats(observations || []), [observations]);
  const cx = useStyles();
  const [paperSize, setPaperSize] = useState('a4');
  const [print, setPrint] = useState(false);
  const [fieldState, setFieldState] = useState(() => {
    var _context, _context2;

    // Lazy initial state to avoid this being calculated on every render
    return _mapInstanceProperty(_context = _filterInstanceProperty(_context2 = _Object$keys(stats)).call(_context2, key => {
      // Hacky: don't include categoryId and notes in options of fields you can hide
      const fieldKey = JSON.parse(key);
      const fieldKeyString = _Array$isArray(fieldKey) ? fieldKey[0] : fieldKey;
      if (hiddenTags[fieldKeyString]) return false;
      return true;
    })).call(_context, key => {
      const fieldKey = JSON.parse(key);
      const label = fieldKeyToLabel(fieldKey);
      return {
        id: key,
        hidden: false,
        label: _Array$isArray(label) ? label.join('.') : label
      };
    });
  });
  useLayoutEffect(() => {
    if (!print) return;
    let didCancel = false; // Wait for map to render
    // TODO: SUPER hacky - we need to wait for the map to render

    const timeoutId = _setTimeout(() => {
      if (didCancel) return;
      window.print();
      setPrint(false);
    }, 3000);

    return () => {
      didCancel = true;
      if (timeoutId) clearTimeout(timeoutId);
    };
  }, [print]);
  return /*#__PURE__*/React.createElement(ViewWrapper, {
    observations: observations,
    onUpdateObservation: onUpdateObservation,
    onDeleteObservation: onDeleteObservation,
    presets: presets,
    filter: filter,
    getMediaUrl: getMediaUrl
  }, ({
    onClickObservation,
    filteredObservations,
    getPreset,
    getMedia
  }) => {
    // Get preset with fields filtered out
    const getPresetWithFilteredFields = (observation
    /*: Observation*/
    ) =>
    /*: PresetWithAdditionalFields*/
    {
      var _context3, _context4;

      const preset = getPreset(observation);
      return _Object$assign({}, preset, {
        fields: _filterInstanceProperty(_context3 = preset.fields).call(_context3, hiddenFieldsFilter(fieldState)),
        additionalFields: _filterInstanceProperty(_context4 = preset.additionalFields).call(_context4, hiddenFieldsFilter(fieldState))
      });
    };

    return /*#__PURE__*/React.createElement("div", {
      className: cx.root
    }, /*#__PURE__*/React.createElement(Toolbar, null, /*#__PURE__*/React.createElement(PrintButton, {
      requestPrint: () => setPrint(true),
      changePaperSize: newSize => setPaperSize(newSize),
      paperSize: paperSize
    }), /*#__PURE__*/React.createElement(HideFieldsButton, {
      fieldState: fieldState,
      onFieldStateUpdate: setFieldState
    })), /*#__PURE__*/React.createElement(ReportViewContent, _extends({
      onClick: onClickObservation,
      observations: filteredObservations,
      getPreset: getPresetWithFilteredFields,
      getMedia: getMedia,
      paperSize: paperSize,
      print: print
    }, otherProps)));
  });
};

export default ReportView;

function hiddenFieldsFilter(fieldState
/*: FieldState*/
) {
  return function (field
  /*: Field*/
  )
  /*: boolean*/
  {
    const state = _findInstanceProperty(fieldState).call(fieldState, fs => {
      const id = _JSON$stringify(_Array$isArray(field.key) ? field.key : [field.key]);

      return fs.id === id;
    });

    return state ? !state.hidden : true;
  };
}

const useStyles = makeStyles(theme => ({
  root: {
    position: 'absolute',
    width: '100%',
    top: 0,
    bottom: 0,
    display: 'flex',
    flexDirection: 'column',
    '@media only print': {
      width: 'auto',
      height: 'auto',
      position: 'static',
      backgroundColor: 'inherit',
      display: 'block'
    }
  }
}));
//# sourceMappingURL=ReportView.js.map