// Copyright (c) 2017 PlanGrid, Inc.

import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import 'styles/main.scss';
import withFetching from './fetch-wrapper';

import {
  CsvViewer,
  DocxViewer,
  VideoViewer,
  XlsxViewer,
  XBimViewer,
  PDFViewer,
  ReactPDFViewer,
  UnsupportedViewer,
  PhotoViewerWrapper,
  AudioViewer
} from './drivers';

class FileViewer extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: true
    };
  }

  componentDidMount() {
    const { height, width } = this.props;
    const getContainer = (value) => {
      const container = document.getElementById('pg-viewer');
      let data = 0;
      if (value === 'height') {
        data = container ? container.clientHeight : 0;
      } else {
        data = container ? container.clientWidth : 0;
      }
      return data;
    };
    const clientHeight = height ? this.props.height : getContainer('height');
    const clientWidth = width ? this.props.width : getContainer('width');
    this.setState({ height: clientHeight, width: clientWidth });
  }

  getDriver() {
    const blobResponseProps = Object.assign({}, this.props, {
      responseType: 'blob'
    });
    switch (this.props.fileType) {
      case 'csv': {
        return withFetching(CsvViewer, blobResponseProps);
      }
      case 'xlsx': {
        return withFetching(XlsxViewer, blobResponseProps);
      }
      case 'jpg':
      case 'jpeg':
      case 'gif':
      case 'bmp':
      case 'svg':
      case 'png': {
        return withFetching(PhotoViewerWrapper, this.props);
      }
      case 'pdf': {
        return withFetching(ReactPDFViewer, this.props);
      }
      case 'pdf2': {
        return withFetching(PDFViewer, this.props);
      }
      case 'docx': {
        return withFetching(DocxViewer, this.props);
      }
      case 'mp3': {
        return withFetching(AudioViewer, this.props);
      }
      case 'webm':
      case 'mp4': {
        return withFetching(VideoViewer, this.props);
      }
      case 'wexbim': {
        return withFetching(XBimViewer, this.props);
      }
      default: {
        return UnsupportedViewer;
      }
    }
  }

  render() {
    const Driver = this.getDriver(this.props);
    return (
      <div className="pg-viewer-wrapper">
        <div className="pg-viewer" id="pg-viewer">
          <Driver {...this.props} width={this.state.width} height={this.state.height} />
        </div>
      </div>
    );
  }
}

FileViewer.propTypes = {
  fileType: PropTypes.string.isRequired,
  filePath: PropTypes.string.isRequired,
  width: PropTypes.number,
  height: PropTypes.number,
  onError: PropTypes.func,
  errorComponent: PropTypes.element,
  unsupportedComponent: PropTypes.element
};

FileViewer.defaultProps = {
  width: null,
  height: null,
  onError: () => null,
  errorComponent: null,
  unsupportedComponent: null
};

export default FileViewer;
module.exports = FileViewer;
