'use strict';

// Based on: https://raw.github.com/imathis/octopress/master/plugins/blockquote.rb

const titlecase = require('titlecase');

const rFullCiteWithTitle = /(\S.*)\s+(https?:\/\/)(\S+)\s+(.+)/i;
const rFullCite = /(\S.*)\s+(https?:\/\/)(\S+)/i;
const rAuthorTitle = /([^,]+),\s*([^,]+)/;

/**
 * @param {string[]} args
 * @param {Hexo} ctx
 */
const parseFooter = (args, ctx) => {
  const str = args.join(' ');
  if (!str) return '';

  let author = '';
  let source = '';
  let title = '';
  let match;

  if ((match = rFullCiteWithTitle.exec(str))) {
    author = match[1];
    source = match[2] + match[3];
    title = ctx.config.titlecase ? titlecase(match[4]) : match[4];
  } else if ((match = rFullCite.exec(str))) {
    author = match[1];
    source = match[2] + match[3];
  } else if ((match = rAuthorTitle.exec(str))) {
    author = match[1];
    title = ctx.config.titlecase ? titlecase(match[2]) : match[2];
  } else {
    author = str;
  }

  let footer = '';
  if (author) footer += `<strong>${author}</strong>`;

  if (source) {
    const link = source.replace(/^https?:\/\/|\/(index.html?)?$/g, '');
    footer += `<cite><a href="${source}">${title ? title : link}</a></cite>`;
  } else if (title) {
    footer += `<cite>${title}</cite>`;
  }

  return footer;
};

/**
* Blockquote tag
*
* Syntax:
*   {% blockquote [author[, source]] [link] [source_link_title] %}
*   Quote string
*   {% endblockquote %}
*/

module.exports = ctx => function blockquoteTag(args, content) {
  const footer = parseFooter(args, ctx);

  let result = '<blockquote>';
  result += ctx.render.renderSync({text: content, engine: 'markdown'});
  if (footer) result += `<footer>${footer}</footer>`;
  result += '</blockquote>';

  return result;
};

@@ -178,26 +178,24 @@
 (https?:%5C/%5C/
-)(
 %5CS+)%5Cs+(.+)/
@@ -241,10 +241,8 @@
 %5C/%5C/
-)(
 %5CS+)
@@ -593,35 +593,24 @@
 e = match%5B2%5D
- + match%5B3%5D
 ;%0A    title 
@@ -650,17 +650,17 @@
 e(match%5B
-4
+3
 %5D) : mat
@@ -666,9 +666,9 @@
 tch%5B
-4
+3
 %5D;%0A 
@@ -760,19 +760,8 @@
 h%5B2%5D
- + match%5B3%5D
 ;%0A  

Concatenate unnecessarily divided groups