package handlers

import (
	"currenstore/database"
	"time"

	"github.com/gofiber/fiber/v2"
	log "github.com/sirupsen/logrus"
)

func GetCurrencyOnDate(c *fiber.Ctx) error {
	charcode := c.Params("charcode")
	ondate := c.Params("ondate")

	result := database.GetExchangeRateOnDate(charcode, ondate)

	if len(result.Currency_id) != 0 {
		return c.JSON(result)
	}
	GetAndSaveByDate(ondate)

	resultCB := database.GetExchangeRateOnDate(charcode, ondate)

	if len(resultCB.Currency_id) != 0 {
		return c.JSON(resultCB)
	}

	return c.Status(404).JSON("Курс Валюты " + charcode + " за дату " + ondate + " не найдено. Требуется обновить данные. Обратитесь к разработчику.")
}

func GetCurrencyOnDateInterval(c *fiber.Ctx) error {
	charcode := c.Params("charcode")
	startdate := c.Params("startdate")
	enddate := c.Params("enddate")

	result := database.GetExchangeRateOnDateInterval(charcode, startdate, enddate)

	return c.JSON(fiber.Map{
		"currency": result,
	})
}

func GetCurrencyInDate(c *fiber.Ctx) error {
	charcode := c.Params("charcode")
	indate := c.FormValue("indate")

	result := database.GetExchangeRateInDate(charcode, indate)

	return c.JSON(fiber.Map{
		"currency": result,
	})
}

// RestoreCurrencyData - restores empty currency dates with exchange rates
func RestoreCurrencyData(c *fiber.Ctx) error {
	startdate := c.Params("startdate")
	enddate := c.Params("enddate")
	var targetLayout string = "02.01.2006"

	currencyDates := database.RestoreExchangeRateOnDate(startdate, enddate)
	emptyDatesList := mapEmptyDates(startdate, enddate, currencyDates)

	for _, checkDate := range emptyDatesList {
		time.Sleep(2 * time.Second)
		checkDateTime, err := time.Parse("2006-01-02", checkDate)
		if err != nil {
			log.Errorf("TimeDate parsing error: %s", err)
		}
		queryDate := checkDateTime.Format(targetLayout)
		currencyModel := GetCurrencyByDate(queryDate)
		database.SaveExchangeRateToDB(currencyModel, "")
	}

	return c.JSON(fiber.Map{
		"result": emptyDatesList,
	})
}

func mapEmptyDates(sd string, ed string, datesList []string) []string {
	var emptyDatesList []string
	layout := "2006-01-02"
	var err error

	sdDateTime, err := time.Parse(layout, sd)
	edDateTime, err := time.Parse(layout, ed)

	if err != nil {
		log.Errorf("TimeDate parsing error: %s", err)
	}

	for d := sdDateTime; !d.After(edDateTime); d = d.AddDate(0, 0, 1) {
		dateElement := d.Format(layout)
		if !isElementExist(datesList, dateElement) {
			emptyDatesList = append(emptyDatesList, dateElement)
		}
	}

	return emptyDatesList
}

func isElementExist(s []string, str string) bool {
	for _, v := range s {
		if v == str {
			return true
		}
	}
	return false
}
