const Controller = require('libflitter/controller/Controller')

/*
 * Sharing Controller
 * -------------------------------------------------------------
 * Put some description here!
 */
class Sharing extends Controller {
    static get services() {
        return [...super.services, 'models']
    }

    async share_page(req, res) {
        const level = req.form.level
        await req.form.page.share_with(req.form.user, level)
        return res.api({})
    }

    async revoke_page(req, res) {
        await req.form.page.unshare_with(req.form.user)
        return res.api({})
    }

    async page_info(req, res) {
         const data = {
            view: (await req.form.page.view_users).map(x => {
                return {username: x.uid, id: x.id, level: 'view'}
            }),
            update: (await req.form.page.update_users).map(x => {
                return {username: x.uid, id: x.id, level: 'update'}
            }),
            manage: (await req.form.page.manage_users).map(x => {
                return {username: x.uid, id: x.id, level: 'manage'}
            }),
        }

        return res.api(data)
    }

    async get_link(req, res) {
        const KeyAction = this.models.get('auth:KeyAction')
        const in_1_week = new Date
        in_1_week.setDate(in_1_week.getDate() + 7)

        const action = new KeyAction({
            handler: 'controller::api:v1:Sharing.accept_link',
            expires: in_1_week,
            auto_login: false,
            no_auto_logout: true, // THIS IS FINE. It's because the MW requires a traditional sign-in.
        })

        await action.save()
        action.data_set('level', req.form.level)
        action.data_set('PageId', req.form.page.UUID)
        await action.save()

        return res.api({ link: action.auth_url() })
    }

    async accept_link(req, res) {
        if ( !req.user ) return req.security.kickout()
        const Page = this.models.get('api:Page')
        const PageId = req.key_action.data_get('PageId')
        const level = req.key_action.data_get('level')

        const page = await Page.findOne({UUID: PageId})
        await page.share_with(req.user, level)

        return res.redirect(`/i/editor;id=${PageId}`)
    }

}

module.exports = exports = Sharing
