const AuthUser = require('flitter-auth/model/User')

/*
 * Auth user model. This inherits fields and methods from the default
 * flitter-auth/model/User model, however you can override methods and
 * properties here as you need.
 */
class User extends AuthUser {
    static get services() {
        return [...super.services, 'models']
    }

    static get schema() {
        return {...super.schema, ...{
            // other schema fields here
            preferences: {
                dark_mode: { type: Boolean, default: false },
                auto_prefetch: { type: Boolean, default: false },
                default_page: String,
            },
        }}
    }

    async get_root_page() {
        const Page = this.models.get('api:Page')
        return Page.findOne({OrgUserId: this._id, ParentId: '0'})
    }

    async get_accessible_pages() {
        const Page = this.models.get('api:Page')
        const user_page = await this.get_root_page()

        const user_pages = await user_page.visible_flat_children(this)

        let view_pages = await Page.find({ shared_users_view: this._id })
        for ( const page of view_pages ) {
            view_pages = [...view_pages, ...(await page.visible_flat_children(this))]
        }

        let update_pages = await Page.find({ shared_users_update: this._id })
        for ( const page of update_pages ) {
            update_pages = [...update_pages, ...(await page.visible_flat_children(this))]
        }

        let manage_pages = await Page.find({ shared_users_manage: this._id })
        for ( const page of manage_pages ) {
            manage_pages = [...manage_pages, ...(await page.visible_flat_children(this))]
        }

        const all_pages = [...user_pages, ...view_pages, ...update_pages, ...manage_pages].filter(x => !x.virtual)
        const uniq_page_obj = {}
        for ( const page of all_pages ) {
            uniq_page_obj[page.UUID] = page
        }

        return Object.values(uniq_page_obj)
    }

    // Other members and methods here
}

module.exports = exports = User
