<?php

namespace Mnv\Core\JSONParser;

use Exception;
use Mnv\Core\JSONParser\Parser\JSONParser;
use Mnv\Core\JSONParser\Writer\JSONWriter;
use Mnv\Core\JSONParser\Exception\FileException;

/**
 * Class JSONParser
 * @package JSONParser
 */
class JSONFactory
{
    /**
     * @var  JSONParser
     */
    public JSONParser $parser;

    /**
     * @var JSONWriter
     */
    public JSONWriter $writer;

    /**
     * @var array
     */
    protected array $validParserTypes = array('XML', 'CSV', 'TSV', 'HTML', 'JSON');
    protected array $validWriterTypes = array('XML', 'CSV', 'TSV', 'HTML', 'JSON');

    /**
     * JSONParser constructor.
     * @param string $filetype Set the filetype of the file which will be parsed (XML/CSV/TSV/HTML/JSON)
     * @throws Exception
     */
    public function __construct(string $filetype = 'JSON')
    {
        $this->constructParser($filetype);
        $this->constructWriter($filetype);
    }

    /**
     * Construct a SimpleExcel Parser
     *
     * @param    string  $filetype   Set the filetype of the file which will be parsed (XML/CSV/TSV/HTML/JSON)
     * @throws   Exception           If filetype is neither XML/CSV/TSV/HTML/JSON
     */
    public function constructParser(string $filetype)
    {

        $filetype = strtoupper($filetype);
        if (!in_array($filetype, $this->validParserTypes)) {
            throw new Exception('Filetype '.$filetype.' is not supported', FileException::FILETYPE_NOT_SUPPORTED);
        }
        $parser_class = 'Mnv\Core\JSONParser\Parser\\'.$filetype.'Parser';
        $this->parser = new $parser_class();
    }

    /**
     * Construct a SimpleExcel Writer
     *
     * @param    string  $filetype   Set the filetype of the file which will be written (XML/CSV/TSV/HTML/JSON)
     * @throws   Exception           If filetype is neither XML/CSV/TSV/HTML/JSON
     */
    public function constructWriter(string $filetype)
    {
        $filetype = strtoupper($filetype);

        if (!in_array($filetype, $this->validWriterTypes)) {
            throw new Exception('Filetype '.$filetype.' is not supported', FileException::FILETYPE_NOT_SUPPORTED);
        }
        $writer_class = 'Mnv\Core\JSONParser\Writer\\'.$filetype.'Writer';
        $this->writer = new $writer_class();
    }

    /**
     * Change writer type to convert to another format
     *
     * @param  string  $filetype   Set the filetype of the file which will be written (XML/CSV/TSV/HTML/JSON)
     * @throws Exception
     */
    public function convertTo(string $filetype = 'JSON')
    {
        $this->constructWriter($filetype);
        $this->writer->setData($this->parser->getField());
    }

}