package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

	"github.com/bwmarrin/discordgo"
)

func loadConfig() {
	var c Config
	confFile, _ := ioutil.ReadFile(configFile)
	err := json.Unmarshal([]byte(confFile), &c)
	if err != nil {
		log.LogErrorType(err)
		return
	}
	config = c

	if time.Since(config.BumpTime) < (2 * time.Hour) {
		bump = false
	} else {
		bump = true
	}

	if config.Stats == nil {
		config.Stats = make(map[string]int)
	}
	if config.Unverified == nil {
		config.Unverified = make(map[string]time.Time)
	}
	if config.Verifications == nil {
		config.Verifications = make(map[string]Verification)
	}
	if config.Probations == nil {
		config.Probations = make(map[string]time.Time)
	}

	log.LogInfo("Setup completed using config file.")
}

func saveConfig() {
	defer log.PanicSafe()
	file, err := json.Marshal(config)
	if err != nil {
		log.LogErrorType(err)
	}
	err = ioutil.WriteFile(configFile, file, 0600)
	if err != nil {
		log.LogErrorType(err)
	}
}

func adminInteraction(s *discordgo.Session, m string) {
	defer log.PanicSafe()
	admin, _ := s.GuildMember(config.GuildID, m)
	counter, ok := config.Stats[admin.User.ID]
	if !ok {
		config.Stats[admin.User.ID] = 1
	} else {
		config.Stats[admin.User.ID] = counter + 1
	}

}

func activeInteraction(s *discordgo.Session, m string) {
	defer log.PanicSafe()
	user, _ := s.GuildMember(config.GuildID, m)
	counter, ok := config.Stats[user.User.ID]
	if !ok {
		config.Activity[user.User.ID] = 1
	} else {
		config.Activity[user.User.ID] = counter + 1
	}

}

func rebootBump() {
	time.Sleep(time.Until(config.BumpTime.Add(2 * time.Hour)))
	dg.ChannelMessageSend(config.AdminChannel, "!d bump is ready")

}

func bumpTimer(s *discordgo.Session) {
	if !bump {
		return
	}
	bump = false
	config.BumpTime = time.Now()
	time.Sleep(2 * time.Hour)
	if time.Since(lastActiveTime) < (5 * time.Minute) {
		s.ChannelMessageSend(lastActiveChan, "!d bump is ready, please use it. (say \"!d bump\" without the quotes)")
	}
	s.ChannelMessageSend(config.AdminChannel, "!d bump is ready.")
	bump = true
}

func purgeTimer(s *discordgo.Session) {
	for {
		runPurge(s)
		saveConfig()
		if time.Since(lastActiveTime) > 4*time.Hour && time.Since(startupTime) > 12*time.Hour {
			log.LogInfo("Restarting.")
			saveConfig()
			os.Exit(0)
		}
		time.Sleep(20 * time.Minute)
	}
}

func (v Verification) prettyPrint() string {
	ret := ""
	ret += fmt.Sprintf("```%+v has marked %+v's verification as %+v\n", v.Admin, v.Username, v.Status)
	ret += fmt.Sprintf("Submitted: %+v\nClosed: %+v\n", v.Submitted, v.Closed)
	ret += fmt.Sprintf("Turnaround time: %+v```", time.Since(v.Submitted))
	ret += fmt.Sprintf("\n%+v", v.Photo)
	return ret
}

func storeVerification(v Verification) {
	defer log.PanicSafe()
	fileURL, _ := url.Parse(v.Photo)
	path := fileURL.Path
	segments := strings.Split(path, "/")

	fileName := segments[len(segments)-1]
	file, _ := os.Create(fmt.Sprintf("./verifications/%s-%s-%s", v.UserID, v.Username, fileName))
	client := http.Client{
		CheckRedirect: func(r *http.Request, via []*http.Request) error {
			r.URL.Opaque = r.URL.Path
			return nil
		},
	}
	resp, err := client.Get(v.Photo)
	if err != nil {
		log.LogError("Unable to download verification %s-%s-%s", v.UserID, v.Username, fileName)
	}
	defer resp.Body.Close()
	defer file.Close()
	_, err = io.Copy(file, resp.Body)
	if err != nil {
		log.LogError("Unable to store verification %s-%s-%s", v.UserID, v.Username, fileName)
	}
}