<?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\Source;

class Sources {
  use Json;

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