<?php
namespace Meramo\mrm_be\Task;

use \TYPO3\CMS\Core\Utility\GeneralUtility;
use \TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
use \Meramo\mrm_be\Mongoer as Mongoer;

class RedirectsFromMysqlToMongo extends  \TYPO3\CMS\Scheduler\Task\AbstractTask {
    public function execute(){
        $connection = GeneralUtility::makeInstance(ConnectionPool::class);

        $redirectsQueryBuilder = $connection->getQueryBuilderForTable('sys_redirect');
        $redirectsQueryBuilder->getRestrictions()->removeAll()
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class))
        ;

        $mongoRedirects = [];

        $selectStatement = $redirectsQueryBuilder
                        ->select('uid','source_path', 'target', 'target_statuscode')
                        ->from('sys_redirect')
                        ->where(
                            $redirectsQueryBuilder->expr()->eq('deleted', 0)
                        )
                        ->andwhere(
                            $redirectsQueryBuilder->expr()->eq('disabled', 0)
                        )
                        ->execute();

        $results = $selectStatement->fetchAll();

        Mongoer::sendRequest("forwardings", "deleteAll", null);

        foreach($results as $k => $redirect) {
            $data = [
                'pageuid' => $redirect['uid'],
                'source' => $redirect['source_path'],
                'target' => $redirect['target'],
                'statusCode' => $redirect['target_statuscode'],

            ]; 

            Mongoer::sendRequest('forwardings', 'save', $data);
        }

        return TRUE;                        
    }

    private function log($msg, $isString = true){
        if(!$isString){
          $msg = json_encode($msg, JSON_PRETTY_PRINT);
        }
        file_put_contents('/var/www/html/typo3temp/debug.log', $msg.PHP_EOL, FILE_APPEND);
      }
}