package wctools

import (
	"encoding/json"
	"errors"
	"github.com/golang/protobuf/proto"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/model"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/model/tariff"
	"strings"
	"time"
	"fmt"
)

var DaysOfWeek = map[string]string{
	"Monday":    "понедельник",
	"Tuesday":   "вторник",
	"Wednesday": "среда",
	"Thursday":  "четверг",
	"Friday":    "пятница",
	"Saturday":  "суббота",
	"Sunday":    "воскресенье",
}

var MonthsOfYear = map[string]string{
	"January":   "января",
	"February":  "февраля",
	"March":     "марта",
	"April":     "апреля",
	"May":       "мая",
	"June":      "июня",
	"July":      "июля",
	"August":    "августа",
	"September": "сентября",
	"October":   "октября",
	"November":  "ноября",
	"December":  "декабря",
}

func IsValidMessage(message []byte, expectedServiceKey string) ([]model.PrivilegeMessage, string, error) {
	var decodedMessage tariff.TariffMessage
	err := proto.Unmarshal(message, &decodedMessage)
	fmt.Println("IVM", err, string(message))
	if err != nil {
		return nil, "", err
	}

	if decodedMessage.UserID == "" || len(decodedMessage.Privileges) == 0 {
		return nil, "", errors.New("Invalid message structure")
	}

	privileges := decodedMessage.Privileges
	userID := decodedMessage.UserID

	var validPrivileges []model.PrivilegeMessage
	for _, privilege := range privileges {
	fmt.Println("IVM1", privilege.ServiceKey, privilege)
		if IsServiceKeyValid(privilege.ServiceKey, expectedServiceKey) {
			validPrivileges = append(validPrivileges, model.PrivilegeMessage{
				PrivilegeID: privilege.PrivilegeID,
				ServiceKey:  privilege.ServiceKey,
				Type:        model.PrivilegeType(privilege.Type),
				Value:       privilege.Value,
				Amount:      privilege.Amount,
			})
		}
	}

	if len(validPrivileges) == 0 {
		return nil, "", errors.New("No valid privileges found")
	}

	return validPrivileges, userID, nil
}

func IsServiceKeyValid(actualServiceKey, expectedServiceKey string) bool {
	return actualServiceKey == expectedServiceKey
}

func FindPrivilegeName(privilegeID string) string {
	for _, p := range model.Privileges {
		if p.PrivilegeID == privilegeID {
			return p.Name
		}
	}
	return ""
}

func ProcessAnswer(answer string) (model.ResultContent, error) {
	content := model.ResultContent{}
	err := json.Unmarshal([]byte(answer), &content)
	if err != nil {
		return model.ResultContent{}, err
	}
	return content, nil
}

func ProcessQuiz(quiz string) (model.QuizConfig, error) {
	quizConfig := model.QuizConfig{}
	err := json.Unmarshal([]byte(quiz), &quizConfig)
	if err != nil {
		return model.QuizConfig{}, err
	}
	return quizConfig, nil
}

func HasUnlimitedPrivilege(privileges []model.ShortPrivilege) bool {
	for _, privilege := range privileges {
		if privilege.PrivilegeID == "quizUnlimTime" {
			return IsPrivilegeExpired(privilege)
		}
	}
	return false
}

func IsPrivilegeExpired(privilege model.ShortPrivilege) bool {
	expirationTime := privilege.CreatedAt.Add(time.Duration(privilege.Amount) * 24 * time.Hour)

	currentTime := time.Now()
	return currentTime.Before(expirationTime)
}

func ExtractEmail(key string) string {
	parts := strings.Split(key, ":")
	if len(parts) != 2 {
		return ""
	}
	return parts[1]
}

func HasQuizCntPrivilege(privileges []model.ShortPrivilege) *model.ShortPrivilege {
	for _, privilege := range privileges {
		if privilege.PrivilegeID == "quizCnt" && privilege.Amount > 0 {
			return &privilege
		}
	}
	return nil
}

func ToJSON(data interface{}) (string, error) {
	result, err := json.Marshal(data)
	if err != nil {
		return "", err
	}
	return string(result), nil
}
