<?php
namespace ProVM\Money\Common\Controller;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use ProVM\Common\Factory\Model as ModelFactory;
use ProVM\Common\Define\Controller\Json;
use ProVM\Money\Alias;

class Aliases {
  use Json;

  public function __invoke(Request $request, Response $response, ModelFactory $factory): Response {
    $aliases = $factory->find(Alias::class)->array();
    $output = compact('aliases');
    return $this->withJson($response, $output);
  }
  public function get(Request $request, Response $response, ModelFactory $factory, $alias_id): Response {
    $alias = $factory->find(Alias::class)->one($alias_id);
    $output = [
      'get_data' => compact('alias_id'),
      'alias' => null
    ];
    if ($alias) {
      $output['alias'] = $alias->asArray();
    }
    return $this->withJson($response, $output);
  }
  public function add(Request $request, Response $response, ModelFactory $factory): Response {
    $post = json_decode($request->getBody()->getContents());
    $aliases = [];
    if (is_array($post)) {
      foreach ($post as $obj) {
        if (!is_object($obj)) {
          continue;
        }
        $aliases []= Alias::add($factory, $obj);
      }
    } else {
      $aliases []= Alias::add($factory, $post);
    }
    $output = [
      'post_data' => $post,
      'aliases' => $aliases
    ];
    return $this->withJson($response, $output);
  }
  public function edit(Request $request, Response $response, ModelFactory $factory, $alias_id) {
    $post = json_decode($request->getBody()->getContents());
    $output = [
      'get_data' => compact('alias_id'),
      'post_data' => $post
    ];
    $alias = $factory->find(Alias::class)->one($alias_id);
    $edited = false;
    if ($alias) {
      $edited = $alias->edit($post);
      $output['alias'] = $alias->asArray();
      $output['edited'] = $edited;
    }
    return $this->withJson($response, $output);
  }
  public function delete(Request $request, Response $response, ModelFactory $factory, $alias_id): Response {
    $alias = $factory->find(Alias::class)->one($alias_id);
    $output = ['get_data' => compact('alias_id'), 'alias' => null, 'deleted' => false];
    if ($alias) {
      $output['alias'] = $alias->asArray();
      $status = $alias->delete();
      $output['deleted'] = $status;
    }
    return $this->withJson($response, $output);
  }
}
