import React from 'react';
import superagent from 'superagent';
import cookie from 'react-cookies';

import * as ApiUtils from '../CloudApi/ApiUtils.js';
import InventoryWrapper from './InventoryWrapper.jsx';
import InventoryItemComponent from './InventoryItemComponent.jsx';

export default class InventoryItem extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            inventoryItem: null,
            history: null
        };
    }

    async componentDidMount() {
        await this.reload();
    }

    async reload() {
        try {
            let schemas = await ApiUtils.getFabricatorSchemas();
            this.setState({ schemas });

            const res = await superagent.get(`/api/admin/inventory/item/${this.props.match.params.id}`).accept('json');
            console.log(res.body);
            this.setState({ inventoryItem: res.body });

            const historyRes = await superagent.get(`/api/admin/inventory/item/${this.props.match.params.id}/history`).accept('json');
            this.setState({ history: historyRes.body });
        } catch (e) {
            console.log(e);
        }
    }

    render() {
        if (this.state.inventoryItem) {
            if (this.state.inventoryItem.trackingType && this.state.inventoryItem.trackingType === 'QuantityTracked') {
                return (
                    <div>
                        <InventoryWrapper title={`📥 Inventory Item ${this.state.inventoryItem.type}`} loading={false}>
                            <InventoryItemComponent schemas={this.state.schemas} inventoryItem={this.state.inventoryItem} history={this.state.history} />
                        </InventoryWrapper>
                    </div>
                );
            } else {
                return (
                    <div>
                        <InventoryWrapper title={`📥 Inventory Item ${this.state.inventoryItem.id}`} loading={false}>
                            <InventoryItemComponent schemas={this.state.schemas} inventoryItem={this.state.inventoryItem} history={this.state.history} />
                        </InventoryWrapper>
                    </div>
                );
            }
        } else {
            return null;
        }
    }
}
