<?php 
class RemarkupBlocksParser implements PhabricatorParserIf{

  private $engine = null;
  
  public function parse($text) {
    $blocks = $this->engine->splitTextIntoBlocks($text);
    
    $output = array();
    foreach($blocks as $block) {
        $block['rule'] = get_class($block['rule']);
        $output[] = new Block($block);
    }
    return $output;
  }
  
  
  public function __construct() {
    $this->engine = $this->initialize();
    $this->engine->setMode(PhutilRemarkupEngine::MODE_TEXT);
  }
  
  private function initialize() {
    $engine = new PhutilRemarkupEngine();
    $engine->setConfig('uri.prefix', 'http://www.example.com/');

    $engine->setConfig(
      'uri.allowed-protocols',
      array(
        'http' => true,
        'mailto' => true,
        'tel' => true,
      ));

    $rules = array();
    $rules[] = new PhutilRemarkupEscapeRemarkupRule();
    $rules[] = new PhutilRemarkupMonospaceRule();
    $rules[] = new PhutilRemarkupDocumentLinkRule();
    $rules[] = new PhutilRemarkupHyperlinkRule();
    $rules[] = new PhutilRemarkupBoldRule();
    $rules[] = new PhutilRemarkupItalicRule();
    $rules[] = new PhutilRemarkupDelRule();
    $rules[] = new PhutilRemarkupUnderlineRule();
    $rules[] = new PhutilRemarkupHighlightRule();

    $blocks = array();
    $blocks[] = new PhutilRemarkupQuotesBlockRule();
    $blocks[] = new PhutilRemarkupReplyBlockRule();
    $blocks[] = new PhutilRemarkupHeaderBlockRule();
    $blocks[] = new PhutilRemarkupHorizontalRuleBlockRule();
    $blocks[] = new PhutilRemarkupCodeBlockRule();
    $blocks[] = new PhutilRemarkupLiteralBlockRule();
    $blocks[] = new PhutilRemarkupNoteBlockRule();
    $blocks[] = new PhutilRemarkupTableBlockRule();
    $blocks[] = new PhutilRemarkupSimpleTableBlockRule();
    $blocks[] = new PhutilRemarkupDefaultBlockRule();
    $blocks[] = new PhutilRemarkupListBlockRule();
    $blocks[] = new PhutilRemarkupInterpreterBlockRule();

    foreach ($blocks as $block) {
      if (!($block instanceof PhutilRemarkupCodeBlockRule)) {
        $block->setMarkupRules($rules);
      }
    }

    $engine->setBlockRules($blocks);

    return $engine;
  }

}
