import React from 'react';
import queryString from 'query-string';

import Icon from '../Icon';
import { downloadFileWithUri, uploadFile } from '../../helpers/utility';
import { parseAnnotationFromXml } from '../../helpers/annotation';

import { Separator } from '../../global/otherStyled';
import { Head, IconWrapper } from '../../global/sidebarStyled';

type Props = {
  close: () => void;
  addAnnots: (annotations: AnnotationType[]) => void;
  hasAnnots: boolean;
};

const index: React.FC<Props> = ({ close, addAnnots, hasAnnots }: Props) => {
  const handleExport = (): void => {
    if (hasAnnots) {
      const parsed = queryString.parse(window.location.search);
      let outputPath = `/api/v1/output.xfdf?f=${parsed.token}`;
      if (parsed.watermark) {
        outputPath = `/api/v1/output.xfdf?f=${parsed.token}&user_id=${parsed.watermark}`;
      }
      downloadFileWithUri('output.xfdf', outputPath);
      // downloadFileWithUri('output.xfdf', `http://127.0.0.1:3000${outputPath}`);
    }
  };

  const handleImport = (): void => {
    uploadFile('.xfdf').then(data => {
      const annotations = parseAnnotationFromXml(data);
      addAnnots(annotations);
    });
  };

  return (
    <Head>
      <IconWrapper>
        <Icon glyph="right-back" onClick={close} />
      </IconWrapper>
      <Separator />
      <IconWrapper>
        <Icon glyph="sort" />
      </IconWrapper>
      <IconWrapper onClick={handleExport}>
        <Icon glyph="annotation-export" isDisabled={!hasAnnots} />
      </IconWrapper>
      <IconWrapper onClick={handleImport}>
        <Icon glyph="import" />
      </IconWrapper>
    </Head>
  );
};

export default index;
