<?php

namespace Plainwork\Csv;

// use Plainwork\DateTime\TimeFactory;
// use Plainwork\DateTime\DateTimeFormatter;
use Plainwork\Core\Translate;

class ObjectExporter
{
    public $translate = Translate::class;

    public function csv(array $objects)
    {
        $header = [];

        $ret = [];
        foreach ($objects as $object) {
            $r = $this->buildOne($object);
            foreach ($r as $k => $v) {
                $header[$k] ??= '';
            }
            $ret[] = $r;
        }

    // pad nonexisting
        $count = count($ret);
        for ($i = 0; $i < $count; $i++) {
            $ret[$i] = $this->buildCsvLine($ret[$i] + $header);
        }

        $header = $this->buildCsvLine(array_keys($header));
        array_unshift($ret, $header);

        $ret = join("\n", $ret);
        $ret = $this->translate->translate($ret);

        return $ret;
    }

    private function buildOne(object $m)
    {
        $ret = [];

        $vars = get_object_vars($m);
        foreach ($vars as $k => $v) {
            $ret[$k] = $v;
        }

        return $ret;
    }

    private function buildCsvLine(array $arr, string $sep = ',')
    {
        $ret = [];
        foreach ($arr as $a) {
            if (false !== strpos($a, '"')) {
                $a = str_replace('"', '""', $a);
            }

            $wrap = false;
            if (false !== strpos($a, $sep)) {
                $wrap = true;
            } elseif (false !== strpos($a, "\n")) {
                $wrap = true;
            }

            if ($wrap) {
                $a = '"' . $a . '"';
            }

            $ret[] = $a;
        }
        $ret = join($sep, $ret);

        return $ret;
    }
}