<?php

namespace App\Actions\Phrase;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use App\View\Pages;

class PhraseAction 
{
    private $filename;
    private $view;
    
    public function __construct(String $filename, Pages $view)
    {
	$this->filename = $filename;
	$this->view = $view;
    }

    public function __invoke(ServerRequestInterface $request,
			     ResponseInterface $response, array $args): ResponseInterface
    {
	if($request->getMethod() === 'GET'){
	    $actions = $this->getPhrase();
	    return $this->view->render($request, $response, 'phrase.html', [
		'actions' => $actions
	    ]);
	};

	$phrase = $this->edit_phrase($request->getParsedBody());
	$this->view->set_message("изменения успешно сохранены");
        return $this->view->render($request, $response, 'phrase.html', [
	    'actions' => $phrase
	]);
    }
    
    private function getPhrase(): array
    {
	$actions = [];

	if(($fp = fopen($this->filename, 'r')) !== FALSE){
	    while (($data = fgetcsv($fp, 100, ",")) !== FALSE) {
		$actions[] = ['action' => $data[0],
			      'data' => $data[1]];
	    }
	} else {
	    $actions[] = ['action' => 'play',
			  'data' => 'anonce'];
	};
	return $actions;
    }

    private function edit_phrase($data): array
    {
	/* $data = $request->getParsedBody(); */
	$phrase = [];
	for($i=0;$i < count($data['action']); $i++){
	    $phrase[] = ['action' => $data['action'][$i],
			 'data' => $data['data'][$i]];
	}

	$fp = fopen($this->filename, 'w');
	$temp = [];
	foreach ($phrase as $f) {
	    $el = [];
	    $el[] = $f['action'];
	    $el[] = $f['data'];
	    $temp[] = $el;
	    
	}
	foreach ($phrase as $fields) {
	    fputcsv($fp, $fields);
	}
	
	fclose($fp);
	return $phrase;
    }
    
}



