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

import useStore from '../store';
import useActions from '../actions';

import NavbarComponent from '../components/Navbar';
import Search from './Search';
import Thumbnails from './Thumbnails';
import AnnotationList from './AnnotationList';
import { downloadFileWithUri, printPdf } from '../helpers/utility';
import { delay } from '../helpers/time';

const Navbar: React.FC = () => {
  const [{ navbarState, displayMode, info, totalPage }, dispatch] = useStore();
  const { setNavbar, setLoading } = useActions(dispatch);

  const onClick = (state: string): void => {
    switch (state) {
      case 'export': {
        const parsed = queryString.parse(window.location.search);
        const fileName = atob(info.token as string);
        let outputPath = `/api/v1/output.pdf?f=${info.token}`;
        if (parsed.watermark) {
          outputPath = `/api/v1/output.pdf?f=${
            info.token
          }&user_id=${window.encodeURI(parsed.watermark)}&pages=0-${totalPage}`;
        }

        setLoading(true);
        downloadFileWithUri(fileName, outputPath);
        // downloadFileWithUri(fileName, `http://127.0.0.1:3000${outputPath}`);
        delay(1000).then(() => {
          setLoading(false);
        });
        break;
      }
      case 'print': {
        const parsed = queryString.parse(window.location.search);
        let outputPath = `/api/v1/output.pdf?f=${info.token}`;
        if (parsed.watermark) {
          outputPath = `/api/v1/output.pdf?f=${
            info.token
          }&user_id=${window.encodeURI(parsed.watermark)}&pages=0-${totalPage}`;
        }
        setLoading(true);
        printPdf(outputPath).then(() => {
          setLoading(false);
        });
        // printPdf(`http://127.0.0.1:3000${outputPath}`).then(() => {
        //   setLoading(false);
        // });
        break;
      }
      case navbarState:
        setNavbar('');
        break;
      default:
        setNavbar(state);
        break;
    }
  };

  return (
    <NavbarComponent
      onClick={onClick}
      navbarState={navbarState}
      displayMode={displayMode}
      fileName={
        info.token ? decodeURIComponent(escape(window.atob(info.token))) : ''
      }
    >
      <Search />
      <AnnotationList />
      <Thumbnails />
    </NavbarComponent>
  );
};

export default Navbar;
