<?php

namespace Drupal\basket\Plugins\Stock;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\basket\Plugins\Stock\BasketStockBulkInterface;
use Drupal\Core\Url;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;

abstract class BasketStockBulkBaseForm extends FormBase implements BasketStockBulkInterface {

	protected static $params;
	protected static $Basket;
	protected static $nodes;

    public function __construct($params = []){
        self::$params = $params;
        self::$Basket = \Drupal::service('Basket');
        if(!empty(self::$params['nids'])){
	        self::$nodes = \Drupal::database()->select('node_field_data', 'n')
										->fields('n', ['nid', 'title'])
										->condition('n.nid', self::$params['nids'], 'in')
										->condition('n.default_langcode',1)
										->execute()->fetchAllKeyed();
        }
    }
    public function getFormId(){
        return 'basket_stock_bulk_form';
    }
    public function buildForm(array $form, FormStateInterface $form_state){
    	$form += [
    		'#prefix'		=> '<div id="basket_stock_bulk_form_ajax_wrap">',
    		'#suffix'		=> '</div>'
    	];
        $form['#title'] = self::$Basket->Translate(self::$params['service']['provider'])->t(self::$params['service']['name']);
    	$form['operationType'] = [
    		'#type'			=> 'hidden',
    		'#value'		=> 'bulk-'.self::$params['service']['id']
    	];
		$form['operatinIds'] = [
			'#tree'				=> TRUE
		];
        $rows = [];
		if(!empty(self::$nodes)){
			foreach (self::$nodes as $nid => $title){
				$rows[] = [
					$nid,
					[
						'data'		=> [
							'#type'		=> 'link',
							'#title'	=> $title,
							'#url'		=> new Url('entity.node.canonical', [
								'node'		=> $nid
							],[
								'attributes'=> [
									'target'	=> '_blank'
								]
							])
						]
					]
				];
				$form['operatinIds'][] = [
					'#type'			=> 'hidden',
					'#value'		=> $nid,
				];
			}
		}
		$form['params'] = [
        	'#tree'			=> TRUE,
        	'#parents'		=> [],
        	'#access'		=> !empty($rows),
        ];
        $this->getForm($form['params'], $form_state);
		$form['actions'] = [
			'#type'			=> 'actions',
			'#access'		=> !empty($rows),
			'#weight'		=> 100,
			'submit'		=> [
				'#type'			=> 'submit',
				'#value'		=> self::$Basket->Translate()->t('To apply'),
				'#ajax'			=> [
					'wrapper'		=> 'basket_stock_bulk_form_ajax_wrap',
					'callback'      => '::ajaxSubmit',
            		'progress'      => ['type' => 'fullscreen'],
				],
				'#name'			=> 'runBulk'
			]
		];
		$form['goods'] = [
			'#type'			=> 'details',
			'#title'		=> self::$Basket->Translate()->t('Products'),
			'#open'			=> empty($rows),
			'#weight'		=> 101,
			'table'			=> [
		  		'#theme'		=> 'table',
		  		'#header'		=> [
		  			'ID',
		  			self::$Basket->Translate()->t('Product name')
		  		],
		  		'#rows'			=> $rows,
		  		'#empty'		=> self::$Basket->Translate()->t('No product selected')
			]
		];
        return $form;
    }
    public function submitForm(array &$form, FormStateInterface $form_state){}
    public function ajaxSubmit(array $form, FormStateInterface $form_state){
    	$triggerElement = $form_state->getTriggeringElement();
    	if(!empty($triggerElement['#name'])){
    		switch($triggerElement['#name']){
    			case'runBulk':
    				$operations = [];
    				$transaction = \Drupal::database()->startTransaction();
    				$settings = $this->getBulkSettings($form_state);
    				foreach ($form_state->getValue('operatinIds') as $nid){
    					$operations[] = [[$this, 'formProcessBulk'], [[
                            'nid'      	=> $nid,
                            'settings'  => $settings
                        ]]];
    				}
    				$batch = array(
                        'title'             => self::$Basket->Translate()->t('Apply changes'),
                        'operations'        => $operations,
                        'basket_batch'      => TRUE,
                        'not_content'		=> TRUE
                    );
                    batch_set($batch);
                    unset($transaction);
                    $response = batch_process(Url::fromRoute('basket.admin.pages', ['page_type' => 'stock-product']));
                    $url = $response->getTargetUrl();
                    $response = new AjaxResponse();
				    return $response->addCommand(new RedirectCommand($url));
    			break;
    		}
    	}
    	return $form;
    }
    public function formProcessBulk($info){
    	$this->processBulk($info['nid'], $info['settings']);
    }
}