<?php
namespace App\Service;

use Incoviba\nuevo\Venta\Cierre;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Element\TextBreak;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\Element\TextRun;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Style\Language;

class Borrador
{
	protected $cierre;
	protected $lineas;
	protected $word;
	protected $text;
	
	public function __construct(Cierre $cierre)
	{
		$this->cierre = $cierre;
		$this->lineas = [];
	}
	protected function add(string $str, int $new_line = 0)
	{
		$this->lineas []= $str;
		if ($new_line > 0) {
			$this->newLine($new_line);
		}
	}
	protected function newLine($n = 1)
	{
		for ($i = 0; $i < $n; $i ++) {
			$this->lineas []= '';
		}
	}
	protected function load()
	{
		$this->word = IOFactory::load('borrador-' . $this->cierre->proyecto()->nombre . '.docx');
	}
	protected function extract()
	{
		$this->load();
		$data = [];
		foreach ($this->word->getSections() as $section) {
			foreach ($section->getElements() as $element) {
				$r = $this->elementGet($element);
				$data []= $r;
			}
		}
		if (count($data) > 0) {
			$this->text = $data;
		}
	}
	protected function elementGet($element)
	{
		if ($element instanceof TextBreak) {
			return PHP_EOL;
		}
		if ($element instanceof TextRun) {
			$data = [];
			foreach ($element->getElements() as $e) {
				$data []= $this->elementGet($e);
			}
			return implode('', $data);
		}
		if (!method_exists($element, 'getText')) {
			d($element);
		}
		return $element->getText();
	}
	protected function build()
	{
		if ($this->text == null) {
			$this->extract();
		}
		foreach ($this->text as $line) {
			if ($line == PHP_EOL) {
				$this->newLine();
				continue;
			}
			if (strpos($line, '[[') !== false) {
				$replacer = new Replacer();
				$this->add($replacer->replace($line, $this->cierre));
				continue;
			}
			$this->add($line);
		}
	}
	public function create()
	{
		$output = new PhpWord();
		
		$output->getSettings()->setDecimalSymbol(',');
		$output->getSettings()->setThemeFontLang(new Language(Language::ES_ES));
		
		$section = $output->addSection();
		foreach ($this->lineas as $linea) {
			if ($linea == '') {
				$section->addTextBreak();
				continue;
			}
			$section->addText($linea);
		}
		
		$output->getSettings()->setTrackRevisions(true);
		
		$writer = IOFactory::createWriter($output);
		$filename = 'Borrador ' . $this->cierre->propietario()->nombreCompleto() . ' con ' . $this->cierre->proyecto()->inmobiliaria()->razon_social . '.docx';
		$writer->save($filename);
	}
	public function show()
	{
		$this->build();
		return implode(PHP_EOL, $this->lineas);
	}
}
?>