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



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

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

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

    RPCs = () => [
        this.getHeadCount,
        this.getGuildInfo
    ]

    RPCFeatures = () => [{
        name: 'manageGuild' as 'manageGuild',
        RPCs: () => [
            this.setName,
            this.setRealm,
            this.setDescription
        ]
    }]
    
    getTableDefinitions = () => []

    getHeadCount = async() : Promise<{ rank: Rank; count: number; }[]> => 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(*)']
            }
        })
    )

    getGuildInfo = async () => this.guild.getConfig()
    setName = async (name:string) => this.guild.setConfigKey('name', name)
    setDescription = async (description: string) => this.guild.setConfigKey('description', description)
    setRealm = async (realm:string) => this.guild.setConfigKey('realm', realm)
}