const PouchdbHandler = require('./pouchdbHandler.js').PouchdbHandler

/**
 *  apps
 *
 *  @author Björn Hase
 *  @license hhttps://www.gnu.org/licenses/gpl-3.0.en.html GPL-3
 *  @link https://gitea.node001.net/HerrHase/tellme-bot.git
 *
 */
class TagsStore extends PouchdbHandler {

    constructor() {
        super()

        // add index for apps
        this.createIndex([
            'name'
        ])
    }

    /**
     *
     *
     *  @param  {object} data
     *
     */
    async create(tags) {

        const query = {
            'selector': {
                'name': {
                    '$in': tags
                }
            }, 'fields': [
                'name'
            ]
        }

        // check for existings tags and remove
        // adding tags that are not removed
        this.db.find(query).then((documents) => {
            if (documents.docs && documents.docs.length > 0) {
                documents.docs.forEach(data, () => {

                    const index = tags.indexOf(data.name)

                    if (index >= 0) {
                        tags.splice(index, 1)
                    }
                })
            }

            if (tags.length > 0) {
                tags.forEach((tag) => {
                    await this.db.post({
                        'name': tag
                    })
                })
            }
        })
    }

    /**
     *
     *
     *  @param  {object} data
     *
     */
    async remove(tags) {

        const query = {
            'selector': {
                'name': {
                    '$in': tags
                }
            }, 'fields': [
                'name'
            ]
        }

        // check for existings tags and remove
        // adding tags that are not removed
        this.db.find(query).then((documents) => {
            if (documents.docs && documents.docs.length > 0) {
                documents.docs.forEach(data, () => {

                    const index = tags.indexOf(data.name)

                    if (index >= 0) {
                        tags.splice(index, 1)
                    }
                })
            }

            if (tags.length > 0) {
                tags.forEach((tag) => {
                    await this.db.post({
                        'name': tag
                    })
                })
            }
        })
    }

    /**
     *  find apps
     *
     *  @return {mixed}
     *
     */
    find() {
        const query = {
            'fields': [
                'name'
            ]
        }

        return this.db.find(query).then((documents) => {
            return documents.docs
        })
    }

}

module.exports.TagsStore = TagsStore