<?php

namespace IMATHUZH\Qfq\Core\Renderer\FormElement\Base;

use IMATHUZH\Qfq\Core\Form\Chat;
use IMATHUZH\Qfq\Core\Form\FormElement\AbstractFormElement;
use IMATHUZH\Qfq\Core\Helper\HelperFormElement;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\Renderer\FormElement\NativeRenderer;

class ChatRenderer extends NativeRenderer {

    /**
     * @inheritDoc
     */
    public function renderInput(AbstractFormElement $fe): string {
        if (isset($fe->attributes[FE_INPUT_EXTRA_BUTTON_LOCK])) {
            $fe->cssClasses[] = 'qfq-disabled';
        }
        $chatFieldsetStart = '<fieldset ' . Support::arrayToXMLAttributes($fe->htmlAttributes) . ' class="' . implode(' ', $fe->cssClasses) . '">';
        $fe->attributes = HelperFormElement::prepareExtraButton($fe->attributes, true);
        if ($fe->attributes[FE_LABEL] !== '' && $fe->attributes[FE_BS_LABEL_COLUMNS] == 0) {
            $chatFieldsetStart .= '<legend>' . $fe->attributes[FE_LABEL] . '</legend>';
        }
        $chatFieldsetEnd = '</fieldset>';

        $fe->windowHtmlAttributes[DATA_CHAT_CONFIG] = htmlentities($fe->windowHtmlAttributes[DATA_CHAT_CONFIG]);

        $chatHead = '<div class="qfq-chat-window" ' . Support::arrayToXMLAttributes($fe->windowHtmlAttributes) . '><span class="fas fa-search chat-search-activate qfq-skip-dirty"></span><div class="chat-search"><input type="text" class="chat-search-input qfq-skip-dirty" placeholder="Search..."><button class="chat-search-btn qfq-skip-dirty">Search</button><span class="chat-search-info"></span></div><div class="chat-messages">';
        $chatTail = '</div></div>';


        if (empty($fe->jsonChat[FE_TYPE_CHAT])) {
            $chatContent = '<div class="chat-no-message"><span class="label label-default">No messages found</span></div>';
        } else {
            $chatContent = '<div class="chat-loader-container" style="display: none;"><div class="chat-loader"></div></div>';
        }

        // textarea
        $textarea = '<textarea ';
        $textarea .= HelperFormElement::getAttributeFeMode($fe->attributes[FE_MODE], false) . ' ';
        $textarea .= Support::arrayToXMLAttributes($fe->textAreaAttributes);
        $textarea .= '>' . htmlentities($fe->value) . '</textarea>';

        $chatSubmit = '<div class="chat-submit-button"><i class="fas fa-paper-plane"></i></div>';
        $inputContainer = '<div class="chat-input-container">' . $textarea . '<div class="button-stack">' .$chatSubmit . $fe->attributes[FE_TMP_EXTRA_BUTTON_HTML] . '</div></div>';

        //$wrapSetupClass = $this->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_CLASS] ?? '';
        //$json = $this->getFormElementForJson($htmlFormElementName, $value, $formElement, $wrapSetupClass);

        // Concat chat html elements and return
        return $chatFieldsetStart . $chatHead . $chatContent . $chatTail . $inputContainer . $chatFieldsetEnd . $fe->attributes[FE_INPUT_EXTRA_BUTTON_INFO];
    }
}