import _ from 'underscore';
import ultramarked from 'ultramarked';
import linkify from 'gfm-linkify';

const DIV = document.createElement('div');

function getElement(text, repoOwner, repoName) {
  DIV.innerHTML = '';
  if (!text) { return DIV; }
  let html = null;
  if (repoOwner) {
    const context = repoOwner + '/' + repoName;
    html = ultramarked(linkify(text, context));
  } else {
    html = ultramarked(linkify(text));
  }
  DIV.innerHTML = html;
  return DIV;
}

// Calculates the task list count by rendering the Markdown in the DOM and
// then counting the number of `<li>[x] ...</li>` elements
export function getTaskCounts(text) {
  const div = getElement(text);
  let taskFinishedCount = 0;
  let taskUnfinishedCount = 0;
  _.each(div.querySelectorAll('li'), (listItem) => {
    if (/^\[x\]\ /.test(listItem.textContent)) {
      taskFinishedCount++;
    } else if (/^\[\ \]\ /.test(listItem.textContent)) {
      taskUnfinishedCount++;
    }
  });
  const taskTotalCount = taskFinishedCount + taskUnfinishedCount;
  return {taskFinishedCount, taskTotalCount};
}

export function getIssueDueAt(text) {
  // TODO: Maybe parse using the local timezone
  const div = getElement(text);
  const el = div.querySelector('date.due');
  if (el) {
    // either use the datetime attribute, or the text
    const attr = el.getAttribute('datetime');
    if (attr) {
      return Date.parse(attr); // TODO: Parse the date and make sure it is valid
    } else if (el.textContent){
      return Date.parse(el.textContent);
    } else {
      console.error('Invalid due date format')
    }
  }
  return null;
}

// From https://help.github.com/articles/closing-issues-via-commit-messages/
export const PULL_REQUEST_ISSUE_RELATION = {
  'close': 'closed by',
  'closes': 'closed by',
  'closed': 'closed by',
  'fix': 'fixed by',
  'fixes': 'fixed by',
  'fixed': 'fixed by',
  'resolve': 'resolved by',
  'resolves': 'resolved by',
  'resolved': 'resolved by'
};

const CLOSE_STRINGS = Object.keys(PULL_REQUEST_ISSUE_RELATION);


// Find all links in the Issue body to other issues or Pull Requests
export function getRelatedIssues(text, repoOwner1, repoName1) {
  const div = getElement(text, repoOwner1, repoName1);
  const relatedIssues = [];
  _.each(div.querySelectorAll('a[href^="https://github.com/"]'), (link) => {
    const href = link.getAttribute('href');
    // match `https://github.com/[repoOwner]/[repoName]/issues/[number]`
    const matches = href.match(/^https\:\/\/github\.com\/([^\/]+)\/([^\/]+)\/(pulls|issues)\/(\d+)$/);
    if (matches) {
      const [, repoOwner, repoName, , number] = matches;
      // Check if the previous node ends with "fixes" or "closes"
      let fixes = false;
      let prevWord = null;
      const prevNode = link.previousSibling;
      if (prevNode && prevNode.nodeType === Node.TEXT_NODE) {
        // pull out the last word
        const prevTexts = prevNode.textContent.trimRight().split(' ');
        prevWord = prevTexts[prevTexts.length - 1].toLowerCase();
        if (CLOSE_STRINGS.indexOf(prevWord) >= 0) {
          fixes = prevWord;
        }
      }
      relatedIssues.push({repoOwner, repoName, number, fixes, prevWord});
    }
  });
  return relatedIssues;
}

@@ -21,16 +21,45 @@
 score';%0A
+import moment from 'moment';%0A
 import u
@@ -1342,18 +1342,17 @@
   const 
-at
+s
 tr = el.
@@ -1375,16 +1375,34 @@
 tetime')
+ %7C%7C el.textContent
 ;%0A    if
@@ -1403,18 +1403,17 @@
     if (
-at
+s
 tr) %7B%0A  
@@ -1420,115 +1420,180 @@
     
-return Date.parse(attr); // TODO: Parse the date and make sure it is valid%0A    %7D else if (el.textContent)%7B%0A
+let date = moment(str, 'MM/DD');%0A      if (date.isValid()) %7B%0A        return date.toDate().getTime();%0A      %7D else %7B%0A        // fall back to parsing using the Date object%0A  
     
@@ -1616,24 +1616,22 @@
 rse(
-el.textContent);
+attr);%0A      %7D
 %0A   
@@ -1660,17 +1660,17 @@
 e.error(
-'
+%60
 Invalid 
@@ -1684,18 +1684,41 @@
 e format
-')
+ for %22$%7Bel.outerHTML%7D%22%60);
 %0A    %7D%0A 

support `mm/dd` format for Issue due dates