// Copyright (c) 2017 PlanGrid, Inc.

import React, { Component } from 'react';
import mammoth from 'mammoth';

import 'styles/docx.scss';
import Loading from '../loading';

export default class extends Component {
  constructor(props) {
    super(props);

    this.state = {
      guid: "docx"
    }
  }

  componentDidMount() {
    this.setState({
      guid: this.generateUUID()
    }, () => {
      const jsonFile = new XMLHttpRequest();
      jsonFile.open('GET', this.props.filePath, true);
      jsonFile.send();
      jsonFile.responseType = 'arraybuffer';
      jsonFile.onreadystatechange = () => {
        if (jsonFile.readyState === 4 && jsonFile.status === 200) {
          mammoth.convertToHtml(
            { arrayBuffer: jsonFile.response },
            { includeDefaultStyleMap: true },
          )
            .then((result) => {
              const docEl = document.createElement('div');
              docEl.className = 'document-container';
              docEl.innerHTML = result.value;
              document.getElementById(this.state.guid).innerHTML = docEl.outerHTML;
            })
            .catch((a) => {
              console.log('alexei: something went wrong', a);
            })
            .done();
        }
      };
    })
  }

  generateUUID = ()=> {
    const placeholder = [1e7]+-1e3+-4e3+-8e3+-1e11;
    const uid = () => {
      const id = crypto.getRandomValues(new Uint8Array(1));
      return (uid ^ id[0] & 15 >> uid / 4).toString(16)
    }
    return placeholder.replace(/[018]/g, uid)
  }

  render() {
    return (
      <div id={this.state.guid}>
        <Loading />
      </div>);
  }
}
