import { ConfigLoader } from "loadson";
import { Inject, Module } from "../../Injector/ServiceDecorator";
import { GuildManagerFeatureIfc, GuildManagerIfc } from "./RPCInterface";
import { FrontworkAdmin } from "../../Admin/Admin";
import { FrontworkComponent } from "../../Types/FrontworkComponent";
import { _Rank, Rank } from "../../Types/Types";
import { IAdmin } from "../../Admin/Interface";

export type Guild = {
    name: string
    realm: string
    description: string
}

@Module()
export class GuildManager
implements FrontworkComponent<GuildManagerIfc, GuildManagerFeatureIfc>{

    name = "GuildManager" as "GuildManager";    
    
    @Inject(IAdmin)
    private admin

    guild: ConfigLoader<Guild>

    constructor(){
        this.guild = new ConfigLoader({
            name: "guild",
            getDefaultConfig: () => {
                return <Guild>{
                    name: "Tranquil",
                    realm: "Gandling EU",
                    description: "Wee woo"
                }
            }
        }, "./config")
    }

    exportRPCs = () => [{
        name: 'getHeadCount' as 'getHeadCount',
        call: this.headCount
    },{
        name: 'getGuildInfo' as 'getGuildInfo',
        call: async () => this.guild.getConfig()
    }]

    exportRPCFeatures = () => [{
        name: 'manageGuild' as 'manageGuild',
        exportRPCs: () => [{
            name: 'setName' as 'setName',
            call: async (name:string) => this.guild.setConfigKey('name', name)
        },{
            name: 'setRealm' as 'setRealm',
            call: async (realm:string) => this.guild.setConfigKey('realm', realm)
        }, {
            name: 'setDescription' as 'setDescription',
            call: async (description: string) => this.guild.setConfigKey('description', description)
        }]
    }]
    
    getTableDefinitions = () => []

    headCount = async () => await Promise.all(
        _Rank.map(async r => {
            const res = await this.admin.knex
            .select('*')
            .from('users')
            .where('rank', '=', r)
            .first()
            .count()

            return <{rank:Rank, count: number}>{
                rank:  r,
                count: res['count(*)']
            }
        })
    )

}