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 has-padding-small is-radiusless">
          <div className="media">
            <div className="media-content">
              <div className="content">
                { !compact && 
                  <nav className="level">
                    <div className="level-left">
                      <div className="level-item">
                        <a target="_blank" href={issueURL}><strong>{`#${card.issue.number}`}</strong></a>
                      </div>
                      { !compact && 
                        <div className="level-item">
                          <a target="_blank" href={projectURL}>{card.project}</a>
                        </div>
                      }
                    </div>
                    <div className="level-right">
                      {
                        card.issue.assignee && !compact ?
                          <div className="level-item">
                            <small>{`@${card.issue.assignee.login}`}</small>
                          </div>
                        : null
                      }
                    </div>
                  </nav>
                }
                { compact &&
                  <a target="_blank" className="mr-1" href={issueURL}><strong>{`#${card.issue.number}`}</strong></a>
                }
                <span>{card.issue.title ? card.issue.title : ''}</span>
              </div>
              { !compact &&
                <nav className="level">
                  <div className="level-left"></div>
                  <div className="level-right">
                    <div className="level-item is-size-7">
                      {card.issue.milestone ? card.issue.milestone.title : ''}
                    </div>
                  </div>
                </nav>
              }
            </div>
          </div>
        </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],
  };
}