import React, {Component} from 'react';
import {connect} from 'react-redux';
import OrderDocumentsGroup from './OrderDocumentsGroup.jsx';
import {orderTexts} from '../../../constants/ordersConstants';
import WiaasBox from "../../../mainComponents/box/WiaasBox";
import {API_SERVER} from "../../../config";
import FileDownloader from "../../../helpers/FileDownloader";

const fileHandler = new FileDownloader();

class OrderDocuments extends Component {

    downloadDocument(orderId, document){
        const fileUrl = `${API_SERVER}/wp-json/wiaas/order/${orderId}/document/${document.key}`;
        fileHandler.download(fileUrl, `${document.name}.${document.extension}`);
    }

    render() {
        const {orderInfo} = this.props;

        return (
            <div id="order-documents" className="order-documents">
                {
                    orderInfo.packages.map(orderPackage => (
                        <OrderDocumentsGroup
                            key={'order-package-' + orderPackage.id}
                            orderId={orderInfo.id}
                            documentsGroup={orderPackage}
                        />))
                }
                {
                    orderInfo.documents && <div>
                        <WiaasBox mainTitle={orderTexts.labels.OTHER_DOCS}>
                            {
                                orderInfo.documents.map((document, index) => (
                                    <a id={'document-' + document.key}  key={'order-document-' + document.key}>
                                        <div onClick={() => {this.downloadDocument(orderInfo.id, document)}} className="document-link-big">
                                            <i className={`fa fa-4x fa-${document.icon}`} aria-hidden="true"></i>
                                            <div>
                                                {document.name}
                                            </div>
                                        </div></a>
                                ))
                            }
                        </WiaasBox>
                    </div>
                }
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    orderInfo: state.processReducer.orderInfo
});
export default connect(mapStateToProps)(OrderDocuments);
