import React from 'react';
import { KanboardCard } from '../../types/kanboard';

export interface IssueCardProps {
  card: KanboardCard
  compact: boolean
}

export class IssueCard extends React.PureComponent<IssueCardProps> {
  render() {
    
    const { card, compact } = this.props;
    const issueURLInfo = extractInfoFromIssueURL(card.issue.url);
    const projectURL = `${issueURLInfo.baseURL}/${issueURLInfo.owner}/${issueURLInfo.projectName}`;
    const issueURL = `${projectURL}/issues/${card.issue.number}`;

    return (
      <div className="kanboard-card">
        <div className={`box ${compact ? 'has-padding-small': ''}`}>
          <div className="media">
            {
              card.issue.assignee && !compact ?
              <div className="media-left">
                <figure className="image is-64x64">
                  <img src={card.issue.assignee.avatar_url} alt="Image" />
                </figure>
                <small>{`@${card.issue.assignee.login}`}</small>
              </div>
              : null
            }
            <div className="media-content">
              <div className="content">
                <p>
                  <a target="_blank" href={issueURL}><strong>{`#${card.issue.number}`}</strong></a>&nbsp;
                  { !compact && card.issue.milestone ? <small>{`- ${card.issue.milestone.title}`}</small> : null }
                  { !compact ? <br /> : ' - ' }
                  <span className="is-size-6">{card.issue.title}</span>
                </p>
              </div>
            </div>
          </div>
          {
            !compact ?
            <div className="level is-mobile" style={{marginTop:'1rem'}}>
              <div className="level-left">
                <small className="level-item"><a href={projectURL}>{card.project}</a></small>
              </div>
              <div className="level-right">
                
              </div>
            </div> :
            null
          }
        </div>
      </div>
    );
  }
}

function extractInfoFromIssueURL(issueURL: string): any|void {
  const pattern = /^(https?:\/\/[^\/]+)\/api\/v1\/repos\/([^\/]+)\/([^\/]+)\/.*$/;
  const matches = pattern.exec(issueURL);
  
  if (!matches) return;

  return {
    baseURL: matches[1],
    owner: matches[2],
    projectName: matches[3],
  };
}