<?php
/**
 * @category Mageants SimpleConfigurable
 * @package Mageants_SimpleConfigurable
 * @copyright Copyright (c) 2017 Mageants
 * @author Mageants Team <info@mageants.com>
 */

namespace Mageants\SimpleConfigurable\Ui;

use Magento\Framework\Api\FilterBuilder;

class Form
{
    public $filterBuilder;
    /**
     * @var array
     */
    public $registryProduct = [];

    /**
     * @param \Magento\Framework\Registry $registry
     * @param FilterBuilder $filterBuilder
     */
    public function __construct(
        \Magento\Framework\Registry $registry,
        FilterBuilder $filterBuilder
    ) {
        $this->registryProduct = $registry;
        $this->filterBuilder = $filterBuilder;
    }

    /**
     * Around get data source data
     *
     * @param \Magento\Ui\Component\Form $subject
     * @return array
     */
    public function aroundGetDataSourceData(\Magento\Ui\Component\Form $subject)
    {
        $dataSource = [];

        $id = $subject->getContext()
            ->getRequestParam($subject->getContext()
                    ->getDataProvider()
                    ->getRequestFieldName(), null);
        $filter = $this->filterBuilder->setField($subject->getContext()
                ->getDataProvider()
                ->getPrimaryFieldName())
            ->setValue($id)
            ->create();
        $subject->getContext()->getDataProvider()->addFilter($filter);

        $data = $subject->getContext()->getDataProvider()->getData();
        $product = $this->registryProduct->registry('current_product');
        if (isset($product) && $product->getTypeId() == 'configurable') {
            foreach ($data as $keyId => $dataValue) {
                if (array_key_exists('configurable-matrix', $dataValue)) {
                    foreach ($dataValue['configurable-matrix'] as $configurableMatrixKey => $configurableMatrix) {
                        $configId = $configurableMatrix['id'];
                        $data[$keyId]['configurable-matrix'][$configurableMatrixKey]['default_value'] = $configId;
                        if ($configId == $product->getIsDefaultSelected()) {
                            $data[$keyId]['configurable-matrix'][$configurableMatrixKey]['checked'] = 1;
                        } else {
                            $data[$keyId]['configurable-matrix'][$configurableMatrixKey]['checked'] = 0;
                        }
                    }
                }
            }
        }
        /*add new field to configurable-matrix ends*/
        if (isset($data[$id])) {
            $dataSource = [
                'data' => $data[$id],
            ];
        } elseif (isset($data['items'])) {
            foreach ($data['items'] as $item) {
                if ($item[$item['id_field_name']] == $id) {
                    $dataSource = ['data' => ['general' => $item]];
                }
            }
        }
        return $dataSource;
    }
}
