import * as React from 'react';
import * as moment from "moment";

import Throbber from "./throbber";

export default class Build extends React.Component<any, any> {
  render () {
    let builds: any = this.props.data;
    let buildsTable: any = [];
    let table: any;
    if (Object.keys(builds).length === 0) {
      buildsTable.push('Loading')
      table = <Throbber />
    }
    else {
      // Get Builds
      builds.forEach((element, i) => {
        let tags: Array<any> = []
        element.tags.forEach(tag => {
          tags.push(
            <span className="building-tag">
              <span className="tag-span rp-tagSpan">
                <i className="fa fa-tag"></i> {tag}
              </span>
            </span>
          );
        });
        let buildId: string = element.id.split('-')[0];
        let phase: string = element.phase ? element.phase : 'Cannot retrieve phase';
        let started: string = element.started ? element.started : 'Cannot retrieve start date';
        let message: string;
        if (element.trigger_metadata && element.trigger_metadata.commit_info && element.trigger_metadata.commit_info.message){
          message = element.trigger_metadata.commit_info.message;
        }
        else {
          message = 'Cannot retrieve message';
        }
        buildsTable.push(
          <tr key={buildId}>
            <td>{phase}</td>
            <td>{buildId}</td>
            <td>{message}</td>
            <td>{moment(started).format('l')}</td>
            <td>{tags}</td>
          </tr>
        )
      });
      // Build the table
      table = (
        <table className="co-table">
          <thead>
            <tr>
              <td></td>
              <td>BUILD ID</td>
              <td>TRIGGERED BY</td>
              <td>DATE STARTED</td>
              <td>TAGS</td>
            </tr>
          </thead>
          <tbody>
            {buildsTable}
          </tbody>
        </table>
      );
    }
    return(
      <div className="row">
        {table}
      </div>
    );
  }
}