package main

import (
	"net/http"
	"sync"

	"github.com/gorilla/mux"
	pluginapi "github.com/mattermost/mattermost-plugin-api"
	"github.com/mattermost/mattermost-server/v5/model"
	"github.com/mattermost/mattermost-server/v5/plugin"
	"github.com/pkg/errors"

	i18n "github.com/larkox/mattermost-plugin-badges/server/i18n"
)

// Plugin implements the interface expected by the Mattermost server to communicate between the server and plugin processes.
type Plugin struct {
	plugin.MattermostPlugin

	// configurationLock synchronizes access to the configuration.
	configurationLock sync.RWMutex

	// configuration is the active plugin configuration. Consult getConfiguration and
	// setConfiguration for usage.
	configuration *configuration

	mm               *pluginapi.Client
	BotUserID        string
	store            Store
	router           *mux.Router
	badgeAdminUserIDs map[string]bool
	i18nBundle       *i18n.Bundle
}

func (p *Plugin) getT(locale string) i18n.TranslationFunc {
	return i18n.LocalizerFunc(p.i18nBundle, locale)
}

// ServeHTTP demonstrates a plugin that handles HTTP requests by greeting the world.
func (p *Plugin) ServeHTTP(c *plugin.Context, w http.ResponseWriter, r *http.Request) {
	r.Header.Add("Mattermost-Plugin-ID", c.SourcePluginId)
	w.Header().Set("Content-Type", "application/json")

	p.router.ServeHTTP(w, r)
}

// See https://developers.mattermost.com/extend/plugins/server/reference/
func (p *Plugin) OnActivate() error {
	p.mm = pluginapi.NewClient(p.API)
	botID, err := p.Helpers.EnsureBot(&model.Bot{
		Username:    "achievements",
		DisplayName: "Achievements Bot",
		Description: "Created by the Achievements plugin.",
	})
	if err != nil {
		return errors.Wrap(err, "failed to ensure badges bot")
	}
	p.BotUserID = botID
	p.store = NewStore(p.API)
	if err := p.store.EnsureDefaultType(p.BotUserID); err != nil {
		p.mm.Log.Warn("Failed to ensure default type", "error", err.Error())
	}
	p.i18nBundle = i18n.Init()
	p.initializeAPI()

	return p.mm.SlashCommand.Register(p.getCommand())
}
