<?php

declare(strict_types=1);

/*
 * This file is part of contao-weinanlieferung-bundle.
 *
 * (c) vonRotenberg
 *
 * @license commercial
 */

namespace vonRotenberg\WeinanlieferungBundle\Migration;

use Contao\CoreBundle\Migration\AbstractMigration;
use Contao\CoreBundle\Migration\MigrationResult;
use Doctrine\DBAL\Connection;

class RebsortenMigration extends AbstractMigration
{
    /** @var Connection */
    private $db;

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }


    public function shouldRun(): bool
    {
        $schemaManager = $this->db->createSchemaManager();

        // If the database table itself does not exist we should do nothing
        if (!$schemaManager->tablesExist(['tl_vr_wa_rebsorte'])) {
            return false;
        }

        $columns = $schemaManager->listTableColumns('tl_vr_wa_rebsorte');

        $isPopulated = (bool) $this->db->executeQuery("SELECT count(id) FROM tl_vr_wa_rebsorte")->fetchOne();

        return !$isPopulated && isset($columns['title']);
    }

    public function run(): MigrationResult
    {
        $time = time();

        $arrRebsorten = [
            ['title' => 'Cabernet'],
            ['title' => 'Cabernet Dorsa'],
            ['title' => 'Chardonnay'],
            ['title' => 'Cuveé'],
            ['title' => 'Gewürztraminer'],
            ['title' => 'Grauer Burgunder'],
            ['title' => 'Grüner Silvaner'],
            ['title' => 'Klingelberger (Riesling)'],
            ['title' => 'Merlot'],
            ['title' => 'Müller-Thurgau'],
            ['title' => 'Muskateller'],
            ['title' => 'Räuschling'],
            ['title' => 'Regent'],
            ['title' => 'Riesling'],
            ['title' => 'Rivaner'],
            ['title' => 'Rotwein Cuvée'],
            ['title' => 'Ruländer'],
            ['title' => 'Sauvignon Blanc'],
            ['title' => 'Sauvitage'],
            ['title' => 'Scheurebe'],
            ['title' => 'Silvaner'],
            ['title' => 'Spätburgunder'],
            ['title' => 'Syrah'],
            ['title' => 'Traminer'],
            ['title' => 'Viognier'],
            ['title' => 'Weißer Burgunder'],
            ['title' => 'Weißwein Cuvée'],
        ];

        for ($i = 0; $i < count($arrRebsorten); $i++)
        {
            $this->db->insert('tl_vr_wa_rebsorte',array_merge($arrRebsorten[$i],['tstamp'=>$time]));
        }

        return $this->createResult(true,'Inserted ' . $i . ' grape varieties.');
    }
}