# JSDoc: Source: schemas/flairSchema.js

# Source: schemas/flairSchema.js

    /*Canopy - The next generation of stoner streaming software
    Copyright (C) 2024-2025 Rainbownapkin and the TTN Community

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.*/

    //NPM Imports
    const {mongoose} = require('mongoose');

    //Local Imports
    const permissionModel = require("./permissionSchema");
    const defaultFlair = require("../../defaultFlair.json");

    /**
     * DB Schema for documents representing chat flair
     */
    const flairSchema = new mongoose.Schema({
        name:{
            type: mongoose.SchemaTypes.String,
            required: true
        },
        displayName:{
            type: mongoose.SchemaTypes.String,
            required: true
        },
        rank: {
            type: mongoose.SchemaTypes.String,
            enum: permissionModel.rankEnum,
            default: "user",
            required: true
        }
    });

    /**
     * Function which runs on server startup to load un-loaded flairs from defaultFlair.json into the DB
     */
    flairSchema.statics.loadDefaults = async function(){
        //Make sure registerFlair function is happy
        const _this = this;

        //Ensure default comes first (.bind(this) doesn't seem to work here...)
        await registerFlair(defaultFlair.default);
        //For each entry in the defaultFlair.json file
        defaultFlair.array.forEach(registerFlair);

        async function registerFlair(flair){
            try{
                //Look for flair matching the one from our file
                const foundFlair = await _this.findOne({name: flair.name});

                //if the flair doesn't exist
                if(!foundFlair){
                    const flairDB = await _this.create(flair);
                    console.log(`Loading default flair '${flair.name} into DB from defaultFlair.json`);
                }

            }catch(err){
                if(flair != null){
                    console.log(`Error loading flair '${flair.name}':`);
                }else{
                    console.log("Error, null flair:");
                }
            }
        }
    }

    module.exports = mongoose.model("flair", flairSchema);