<?php
namespace Neos\Flow\Persistence\Doctrine\Migrations;

use Doctrine\DBAL\FetchMode;
use Doctrine\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
use Ramsey\Uuid\Uuid;

/**
 * Auto-generated Migration: Please modify to your needs! This block will be used as the migration description if getDescription() is not used.
 */
class Version20200902151355 extends AbstractMigration
{

    /**
     * @return string
     */
    public function getDescription()
    {
        return '';
    }

    /**
     * @param Schema $schema
     * @return void
     */
    public function up(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on "mysql".');

        // Create the new table
        $this->addSql('CREATE TABLE newland_toubiz_sync_neos_domain_model_rawjson (persistence_object_identifier CHAR(36) NOT NULL COMMENT \'(DC2Type:guid)\', rawjson LONGTEXT NOT NULL COMMENT \'(DC2Type:json)\', PRIMARY KEY(persistence_object_identifier)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');

        // Add new pointer fields
        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_article ADD rawjsonrelation CHAR(36) DEFAULT NULL COMMENT \'(DC2Type:guid)\'');
        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_event ADD rawjsonrelation CHAR(36) DEFAULT NULL COMMENT \'(DC2Type:guid)\'');

        // Move data
        $this->moveRawJsonIntoRelation('newland_toubiz_sync_neos_domain_model_article');
        $this->moveRawJsonIntoRelation('newland_toubiz_sync_neos_domain_model_event');

        // Drop old fields
        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_article DROP rawjson');
        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_event DROP rawjson');

        // Add indicies
        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_article ADD CONSTRAINT FK_2D54DF93B91F5129 FOREIGN KEY (rawjsonrelation) REFERENCES newland_toubiz_sync_neos_domain_model_rawjson (persistence_object_identifier)');
        $this->addSql('CREATE UNIQUE INDEX UNIQ_2D54DF93B91F5129 ON newland_toubiz_sync_neos_domain_model_article (rawjsonrelation)');

        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_event ADD CONSTRAINT FK_4DAD30E6B91F5129 FOREIGN KEY (rawjsonrelation) REFERENCES newland_toubiz_sync_neos_domain_model_rawjson (persistence_object_identifier)');
        $this->addSql('CREATE UNIQUE INDEX UNIQ_4DAD30E6B91F5129 ON newland_toubiz_sync_neos_domain_model_event (rawjsonrelation)');
    }

    private function moveRawJsonIntoRelation(string $tableName): void
    {
        $selectQuery = sprintf('SELECT persistence_object_identifier,rawjson from %s', $tableName);
        $insertQuery = 'INSERT INTO newland_toubiz_sync_neos_domain_model_rawjson (persistence_object_identifier, rawjson) VALUES (?,?)';
        $updateQuery = sprintf('UPDATE %s SET rawjsonrelation=? WHERE persistence_object_identifier=?', $tableName);

        $result = $this->connection->executeQuery($selectQuery);
        while ($row = $result->fetch(FetchMode::STANDARD_OBJECT)) {
            if (empty($row->rawjson)) {
                continue;
            }
            $id = Uuid::uuid4()->toString();
            $this->addSql($insertQuery, [ $id, $row->rawjson ]);
            $this->addSql($updateQuery, [ $id, $row->persistence_object_identifier ]);
        }
    }


    /**
     * @param Schema $schema
     * @return void
     */
    public function down(Schema $schema)
    {
        // this down() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on "mysql".');

        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_article DROP FOREIGN KEY FK_2D54DF93B91F5129');
        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_event DROP FOREIGN KEY FK_4DAD30E6B91F5129');
        $this->addSql('DROP TABLE newland_toubiz_sync_neos_domain_model_rawjson');
        $this->addSql('DROP INDEX idx_35dc14f03332102a ON neos_flow_resourcemanagement_persistentresource');
        $this->addSql('CREATE INDEX IDX_6954B1F63332102A ON neos_flow_resourcemanagement_persistentresource (sha1)');
        $this->addSql('DROP INDEX UNIQ_2D54DF93B91F5129 ON newland_toubiz_sync_neos_domain_model_article');
        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_article ADD sourcename VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`, ADD authorname VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`, ADD rawjson LONGTEXT CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci` COMMENT \'(DC2Type:json)\', DROP rawjsonrelation');
        $this->addSql('DROP INDEX UNIQ_4DAD30E6B91F5129 ON newland_toubiz_sync_neos_domain_model_event');
        $this->addSql('ALTER TABLE newland_toubiz_sync_neos_domain_model_event ADD rawjson LONGTEXT CHARACTER SET utf8mb4 NOT NULL COLLATE `utf8mb4_unicode_ci` COMMENT \'(DC2Type:json)\', DROP rawjsonrelation');
    }
}
