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 AppsStore extends PouchdbHandler {

    constructor() {
        super()

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

    /**
     *
     *  @param  {object} data
     *  @return {object}
     *
     */
    create(data) {
        return this.db.post(data)
            .then((response) => {
                return this.findOneById(response._id)
            }).catch((error) => {
                console.error(error)
            })
    }

    /**
     *
     *  @param  {object} data
     *  @return {object}
     *
     */
    update(data) {
        return this.db.put(data)
            .then((response) => {
                return this.findOneById(response._id)
            }).catch((error) => {
                console.error(error)
            })
    }

    /**
     *  find one app by id
     *
     *  @param  {string} id
     *  @return {mixed}
     *
     */
    findOneById(id) {
        const query = {
            'fields': [
                '_id',
                '_rev',
                'name',
                'command',
                'description',
                'thumbnail',
                'tags'
            ],
            'selector': {
                '_id' : id
            }
        }

        return this.db.find(query).then((documents) => {
            if (documents.docs.length === 0) {
                return null
            } else {
                return documents.docs[0]
            }
        }).catch((error) => {
            console.error(error)
        })
    }

    /**
     *  find apps
     *
     *  @return {mixed}
     *
     */
    find() {
        const query = {
            'fields': [
                '_id',
                'name',
                'command',
                'description',
                'thumbnail',
                'tags',
                'started_date'
            ],
            'selector': {
                'name': {
                    '$exists': true
                }
            }
        }

        return this.db.find(query).then((documents) => {
            if (documents.warning) {
                console.warning(documents.warning)
            }

            return documents.docs
        }).catch((error) => {
            console.error(error)
        })
    }

}

module.exports.AppsStore = AppsStore