<?php

namespace Leadlion\Autogedal\Ui\Component\Listing\Columns;

use Magento\Backend\Block\Template;

class Attachments extends \Mageplaza\ProductAttachments\Ui\Component\Listing\Columns\Attachments
{
    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     *
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        $blockTemplate = $this->_objectManager->create(Template::class);
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {
                $fileList = $this->_helperData->getFilesByProductId($item['entity_id']);
                $uploadedFiles = $this->prepareUploadedFilesData($fileList->getData());
                $item[$this->getData('name')] = '<a id="mp-attachments-'
                    . $item['entity_id'] . '" style="text-align: center;" href="#">' . __('Add File') . '</a>'
                    .$uploadedFiles;
                $item['mp_attachment_file_data'] = $this->prepareFileData($fileList->getData());
                $item['mp_attachment_file_system'] =
                    $this->_jsonEncode->encode($this->_helperData->getShowOnLocation());
                $item['mp_attachment_loading_url'] = $blockTemplate->getViewFileUrl('images/loader-1.gif');
                $item['mp_attachment_ajax_url'] = $this->_urlBuilder->getUrl(
                    'mpproductattachments/file_attachment/upload',
                    ['form_key' => $blockTemplate->getFormKey()]
                );
                $item['mp_attachment_ajax_save_url'] = $this->_urlBuilder->getUrl(
                    'mpproductattachments/product_grid/save',
                    ['form_key' => $blockTemplate->getFormKey()]
                );
                $item['mp_attachment_ajax_get_config'] = $this->_urlBuilder->getUrl(
                    'mpproductattachments/product_grid/config',
                    ['form_key' => $blockTemplate->getFormKey()]
                );
                $item['mp_attachment_location'] = $this->getAttachmentLocation($item['entity_id']);
            }
        }

        return $dataSource;
    }

    /**
     * @param $collection
     *
     * @return string
     */
    public function prepareUploadedFilesData($collection)
    {
        $fileNames = '<br>';
        if (isset($collection) && count($collection) > 0) {
            foreach ($collection as $item) {
                $fileNames .= $item['name'].'<br>';
            }
        }

        return $fileNames;
    }
}
