import { FriendlyError } from "discord.js-commando";
import config from "config";
import { oneLine } from "common-tags";

import WebcordClient from "lib/WebcordClient";
import AWS from "structures/Feathers";
import Feathers from "structures/Feathers";
import RethinkDB from "structures/RethinkDB";

import logger from "config/logger";
import RethinkDBProvider from "providers/RethinkDBProvider";
import services from "services/";

export default function() {
    const feathers = Feathers();
    const client = new WebcordClient(config.get("discord"), feathers);

    client.db = RethinkDB;
    client.AWS = AWS;
    client.setProvider(new RethinkDBProvider(client.db, "commands"))
    client.registry.registerDefaults();
    client.services = services;

    client
        .on("error", logger.error)
        .once("ready", client.onConnect)
        .on("disconnect", () => { logger.warn("Disconnected!"); })
        .on("reconnecting", () => { logger.warn("Reconnecting..."); })
        .on("commandError", (cmd, err) => {
            if(err instanceof FriendlyError) return;
            logger.error(`Error in command ${cmd.groupID}:${cmd.memberName}`, err);
        })
        .on("commandBlocked", (msg, reason) => {
            logger.info(oneLine`
                Command ${msg.command ? `${msg.command.groupID}:${msg.command.memberName}` : ""}
                blocked; ${reason}
            `);
        })
        .on("commandPrefixChange", (guild, prefix) => {
            logger.info(oneLine`
                Prefix ${prefix === "" ? "removed" : `changed to ${prefix || "the default"}`}
                ${guild ? `in guild ${guild.name} (${guild.id})` : "globally"}.
            `);
        })
        .on("commandStatusChange", (guild, command, enabled) => {
            logger.info(oneLine`
                Command ${command.groupID}:${command.memberName}
                ${enabled ? "enabled" : "disabled"}
                ${guild ? `in guild ${guild.name} (${guild.id})` : "globally"}.
            `);
        })
        .on("groupStatusChange", (guild, group, enabled) => {
            logger.info(oneLine`
                Group ${group.id}
                ${enabled ? "enabled" : "disabled"}
                ${guild ? `in guild ${guild.name} (${guild.id})` : "globally"}.
            `);
        });
    
    if(process.env.NODE_ENV === "development" || process.env.LOG_LEVEL === "debug")
        client.on("warn", logger.warn).on("debug", logger.debug);

    client.start(config.get("port"));
}
