<?PHP
/**
 * Contains a class for keeping the times fulltext index in sync.
 *
 * @author Joshua Ramon Enslin <joshua@museum-digital.de>
 */
declare(strict_types = 1);

/**
 * Class for keeping the times fulltext index in sync.
 */
final class NodaTimeFulltextSync {

    /** @var MDMysqli */
    private MDMysqli $_mysqli_noda;

    /**
     * Removes the obsolete entries.
     *
     * @return void
     */
    public function removeObsolete():void {

        $result = $this->_mysqli_noda->do_read_query("SELECT 1
            FROM `zeiten_fulltext`
            WHERE NOT EXISTS (SELECT 1 FROM `zeiten`
                WHERE `zeiten`.`zeit_id` = `zeiten_fulltext`.`zeit_id`)
            LIMIT 1");

        if ($result->num_rows === 0) {
            $result->close();
            return;
        }
        $result->close();

        $this->_mysqli_noda->do_update_query_large("DELETE FROM `zeiten_fulltext`
            WHERE NOT EXISTS (SELECT 1 FROM `zeiten`
                WHERE `zeiten`.`zeit_id` = `zeiten_fulltext`.`zeit_id`)");

    }

    /**
     * Gets the entries to update.
     *
     * @return array<string>
     */
    public function getNewEntries():array {

        $result = $this->_mysqli_noda->do_read_query("SELECT `zeit_id`,
                `zeit_name`
            FROM `zeiten`
            WHERE NOT EXISTS (SELECT 1
                FROM `zeiten_fulltext`
                WHERE `zeiten`.`zeit_id` = `zeiten_fulltext`.`zeit_id`
                    AND `zeiten`.`zeit_erfasst_am` <= `zeiten_fulltext`.`update_timestamp`)
            LIMIT 10000");

        if ($result->num_rows === 0) {
            $result->close();
            return [];
        }

        $toUpdate = [];

        while ($cur = $result->fetch_assoc()) {
            $zeit_id = (int)$cur['zeit_id'];
            unset($cur['zeit_id']);
            $toUpdate[$zeit_id] = $cur;
        }
        $result->close();

        $tlResult = $this->_mysqli_noda->do_read_query("SELECT `zeit_translation`.`zeit_id`, `trans_name` AS `name`
            FROM `zeit_translation`
            WHERE `zeit_translation`.`zeit_id` IN (" . implode(', ', array_keys($toUpdate)) . ")");

        $translations = [];
        while ($cur = $tlResult->fetch_assoc()) {
            $time_id = (int)$cur['zeit_id'];
            if (empty($translations[$time_id])) {
                $translations[$time_id] = [$cur['name']];
            }
            else $translations[$time_id][] = $cur['name'];
        }
        $tlResult->close();

        $newEntries = [];

        foreach ($toUpdate as $zeit_id => $values) {
            if (isset($translations[$zeit_id])) $values = array_merge($values, $translations[$zeit_id]);
            $newEntries[$zeit_id] = implode(' ', array_unique($values));
        }

        return $newEntries;

    }

    /**
     * Loads the list of entries to update.
     *
     * @return void
     */
    public function update():void {

        if (empty($toUpdate = $this->getNewEntries())) {
            return;
        }

        if (count($toUpdate) > 1) {
            $this->_mysqli_noda->autocommit(false);
        }

        $updateStmt = $this->_mysqli_noda->do_prepare("INSERT INTO `zeiten_fulltext`
            (`zeit_id`, `content`, `update_timestamp`)
            VALUES
            (?, ?, NOW())
            ON DUPLICATE KEY UPDATE `content` = ?,
                `update_timestamp` = NOW()");

        foreach ($toUpdate as $key => $value) {
            $updateStmt->bind_param("iss", $key, $value, $value);
            $updateStmt->execute();
        }

        $updateStmt->close();

        if (count($toUpdate) > 1) {
            $this->_mysqli_noda->commit();
            $this->_mysqli_noda->autocommit(true);
        }

    }

    /**
     * Sync: Wrapper function glueing together the sync process.
     *
     * @return void
     */
    public function sync():void {

        $this->removeObsolete();
        $this->update();

    }

    /**
     * Constructor.
     *
     * @param MDMysqli $mysqli_noda DB connection.
     *
     * @return void
     */
    public function __construct(MDMysqli $mysqli_noda) {

        $this->_mysqli_noda = $mysqli_noda;

    }
}
