<?php


namespace App\Tables;


class CXMacroExporter extends CStructArrayExporter
{
    private $noQuoteCols = true;

    public function noQuotesAround($cols)
    {
        $this->noQuoteCols = $cols;
        return $this;
    }

    /**
     * @return string - mime type for the downloaded file
     */
    protected function getMimeType()
    {
        return  $this->wantDownload ? 'text/x-chdr' : 'text/plain';
    }

    /**
     * @return string - file extension for the downloaded file
     */
    protected function getFileExtension()
    {
        return 'h';
    }

    /**
     * Write the document to stdout ('php://output')
     */
    protected function writeDocument()
    {
        $table = $this->table;

        $any_bool = false;
        $colnames = [];
        $fields = array_map(function (Column $c) use (&$any_bool, &$colnames) {
            if ($c->type == 'bool') $any_bool = true;
            $cname = $this->cify($c->name);
            $colnames[] = $cname;
            return (object)['name' => $c->name, 'type' => $c->type, 'cname' => $cname];
        }, $this->columns);

        $ctablename = 'X_' .strtoupper($this->cify($table->name));

        echo "#ifndef {$ctablename}_H\n".
             "#define {$ctablename}_H\n\n";

        echo "/*\n" . $this->getHeaderComment(' ') . "\n";

        echo
             " Example X macro processing the table: \n".
             " \n";
        echo "   #undef X\n";
        echo "   #define X(".implode(', ', $colnames) .") \\\n".
             "       ...do something with the args\n".
             " \n".
             " Then run it by putting $ctablename somewhere in your C or H file.\n";
        echo "*/\n\n";

        // Now the table itself
        echo "#define ".$ctablename." \\\n";

        $first = true;
        foreach ($this->iterateRows() as $row) {
            if ($first) {
                $first = false;
            } else {
                echo " \\\n";
            }

            echo "    X(";
            $this->dumpRow($fields, $row, $this->noQuoteCols, false);
            echo ")";
        }

        echo "\n\n#endif /* {$ctablename}_H */\n";
    }
}