<?php

// content model events (collections)

$this->on('content.item.save', function($modelName, $data) {

    $model = $this->module('content')->model($modelName);

    if (!in_array($model['type'], ['collection', 'tree'])) {
        return;
    }

    $indexes = $this->module('detektivo')->indexes();
    $toUpdate = [];

    foreach ($indexes as $index) {

        if ($index['type'] !== 'content:collection') continue;
        if (!isset($index['meta']['model']) || $index['meta']['model'] !== $modelName) continue;
        $toUpdate[] = $index;
    }

    if (!count($toUpdate)) return;

    $fields = $model['fields'];

    // does the model have localized fields?
    $hasLocaleFields = false;
    $locales = [];

    foreach ($this->helper('locales')->locales() as $locale) {
        if ($locale['i18n'] == 'default') continue;
        $locales[] = $locale['i18n'];
    }

    foreach ($fields as $field) {
        if (isset($field['i18n']) && $field['i18n']) {
            $hasLocaleFields = true;
            break;
        }
    }

    foreach ($toUpdate as $index) {

        $populate = $index['meta']['populate'] ?? 0;
        $indexLocale = $index['meta']['locale'] ?? false;

        $item = $this->module('content')->item($modelName, ['_id' => $data['_id']], null, ['populate' => $populate]);
        $item['id'] = $item['_id'];
        unset($item['_id']);

        $idx = $this->module('detektivo')->index($index['name']);
        $ids = [$item['id']];
        $documents = [];

        $hasIndexLocaleField = false;

        // collect available locales
        if ($hasLocaleFields) {

            foreach ($index['fields'] as $field) {
                if ($field === 'locale') {
                    $hasIndexLocaleField = true;
                    break;
                }
            }

            foreach ($locales as $locale) {
                $ids[] = "{$item['id']}{$locale}";
            }
        }

        foreach ($ids as $id) {
            $idx->removeDocument($id);
        }

        if ($item['_state'] !== 1) {
            continue;
        }

        if ($indexLocale && count($locales)) {

            $doc = $this->helper('locales')->applyLocales($item, 'default');

            if ($hasIndexLocaleField) {
                $item['locale'] = 'default';
            }

            $documents[] = $doc;

            foreach ($locales as $locale) {

                $doc = $this->helper('locales')->applyLocales($item, $locale);
                $doc['id'] = "{$item['id']}{$locale}";

                if ($hasIndexLocaleField) {
                    $doc['locale'] = $locale;
                }

                $documents[] = $doc;
            }

        } else {
            $documents[] = $item;
        }

        $idx->addDocuments($documents);
    }

});

$this->on('content.remove.before', function($modelName, $filter, $collection) {

    $model = $this->module('content')->model($modelName);

    if (!in_array($model['type'], ['collection', 'tree'])) {
        return;
    }

    $indexes = $this->module('detektivo')->indexes();
    $toUpdate = [];

    foreach ($indexes as $index) {

        if ($index['type'] !== 'content:collection') continue;
        if (!isset($index['meta']['model']) || $index['meta']['model'] !== $modelName) continue;
        $toUpdate[] = $index;
    }

    if (!count($toUpdate)) return;

    $items = (array) $this->dataStorage->find($collection, [
        'fields' => ['_id' => 1],
        'filter' => $filter
    ]);

    if (!count($items)) return;

    $locales = [];

    foreach ($this->helper('locales')->locales() as $locale) {
        if ($locale['i18n'] == 'default') continue;
        $locales[] = $locale['i18n'];
    }

    $ids = [];

    foreach ($items as $item) {

        $ids[] = $item['_id'];

        foreach ($locales as $locale) {
            $ids[] = "{$item['_id']}_{$locale}";
        }
    }

    foreach ($toUpdate as $index) {

        $idx = $this->module('detektivo')->index($index['name']);

        foreach ($ids as $id) {
            $idx->removeDocument($id);
        }

    }
});
