import React from 'react';
import _ from 'lodash';
import { fromUnixTime, formatDistanceToNow } from "date-fns";
import { formatInTimeZone } from 'date-fns-tz'

import constants, { DEFAULT_TIMEZONE } from '../CloudApi/Constants.js';
import * as ApiUtils from '../CloudApi/ApiUtils.js';
import WaxIdBitField from './WaxIdBitField.jsx';
import ToolPathDownloadButton from './ToolPathDownloadButton.jsx';

import { Segment, Modal, Header, Icon, Button, Table, Form, Divider, Label } from 'semantic-ui-react'
import ClickableTableRow from '../Util/ClickableTableRow.jsx';

export default class JobsList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false
        };
    }

    async componentDidMount() {
        this.setState({ loading: true });
        let schemas = await ApiUtils.getFabricatorSchemas();
        this.setState({ schemas });
        this.setState({ loading: false });
    }

    renderJob(job) {
        const createdAtDateTime = fromUnixTime(Math.floor(job.createdAt / 1000));
        const created = formatInTimeZone(createdAtDateTime, DEFAULT_TIMEZONE, 'PPp');
        const waxId = (job.waxIdSnapshots && job.waxIdSnapshots.length > 0) ? job.waxIdSnapshots[0].id : "";

        const updatedDateTime = fromUnixTime(Math.floor(_.last(job.history).createdAt / 1000));
        const updated = formatInTimeZone(updatedDateTime, DEFAULT_TIMEZONE, 'PPp');

        const AWAITING_MANUFACTURE = 11;

        const jobState = Object.entries(this.state.schemas.JobStates).find(entry => entry[1] === job.jobState)[0];

        const machineIdHistory = _.last(_.filter(job.history, item => item.metaData && item.metaData.machineId && item.metaData.machineId.startsWith("cb")));
        return (
            <ClickableTableRow allowClicks={false} href={`/fabricator/job/${job.id}`}>
                <Table.Cell width={1} collapsing>
                    <a style={{textDecoration: "underline" }} href={`/fabricator/job/${job.id}`}>{job.id}</a>
                    {job.name && <p>(Name: <span>{job.name}</span>)</p>}
                    {job.nfcTagId && <p>NFC Tag Id: <Label color="green">{job.nfcTagId}</Label></p>}
                </Table.Cell>
                <Table.Cell width={1} collapsing>{created}</Table.Cell>
                <Table.Cell width={1} collapsing>{updated}</Table.Cell>
                <Table.Cell width={1} collapsing><Label horizontal>{jobState}</Label></Table.Cell>
                <Table.Cell width={1} collapsing>{job.priority}</Table.Cell>
                <Table.Cell width={5}>
                    <WaxIdBitField job={job} />
                </Table.Cell>
                <Table.Cell width={3} collapsing>
                    {machineIdHistory && <p>Machine Id: <Label color="teal">{machineIdHistory.metaData.machineId}</Label></p>}
                    {(job.ipd > 0) && <p>IPD: <Label color="blue">{`${job.ipd}mm`}</Label></p>}
                </Table.Cell>
                <Table.Cell width={1} collapsing>{job.bigOrderId && <Button inverted color="green" size="tiny" href={`/shop/order/${job.bigOrderId}`}><Icon name='shopping bag' />Big order</Button>}</Table.Cell>
            </ClickableTableRow>
        )
    }

    render() {
        if (this.props.loading) {
            return (
                <Segment basic loading={this.props.loading} />
            );
        } else if (this.state.schemas && this.props.jobs) {
            return (
                <Table celled striped compact>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell width={1} collapsing>Job #</Table.HeaderCell>
                            <Table.HeaderCell width={1} collapsing>Created</Table.HeaderCell>
                            <Table.HeaderCell width={1} collapsing>Last Updated</Table.HeaderCell>
                            <Table.HeaderCell width={1} collapsing>State</Table.HeaderCell>
                            <Table.HeaderCell width={1} collapsing>Priority</Table.HeaderCell>
                            <Table.HeaderCell width={5}>WaxId (showing latest)</Table.HeaderCell>
                            <Table.HeaderCell width={3} collapsing>Info</Table.HeaderCell>
                            <Table.HeaderCell width={1} collapsing>Big Order</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    <Table.Body>
                        {this.props.jobs.map(job => this.renderJob(job))}
                    </Table.Body>
                </Table>
            )
        } 
        return null;
    }
}
