/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package form

import (
	"database/sql/driver"
	"net/http"
	"strconv"
	"strings"

	"golang.org/x/text/language"

	"dev.tandem.ws/tandem/camper/pkg/database"
	"dev.tandem.ws/tandem/camper/pkg/locale"
)

type Input struct {
	Name  string
	Val   string
	Error error
}

func (input *Input) setError(err error) {
	input.Error = err
}

func (input *Input) FillValue(r *http.Request) {
	input.FillValueIndex(r, 0)
}

func (input *Input) FillValueIndex(r *http.Request, idx int) {
	var val string
	if vs := r.Form[input.Name]; len(vs) > idx {
		val = vs[idx]
	}
	input.Val = strings.TrimSpace(val)
}

func (input *Input) Value() (driver.Value, error) {
	return input.Val, nil
}

func (input *Input) Int() int {
	i, err := strconv.Atoi(input.Val)
	if err != nil {
		panic(err)
	}
	return i
}

type I18nInput map[string]*Input

func NewI18nInput(locales locale.Locales, name string) I18nInput {
	input := make(I18nInput)
	for lang := range locales {
		input[lang.String()] = &Input{
			Name: name + "." + lang.String(),
		}
	}
	return input
}

func (input I18nInput) FillValue(r *http.Request) {
	for _, inner := range input {
		inner.FillValue(r)
	}
}

func (input I18nInput) FillArray(array database.RecordArray) error {
	for _, el := range array.Elements {
		lang := el.Fields[0].Get()
		if lang == nil {
			continue
		}
		tag, err := language.Parse(lang.(string))
		if err != nil {
			return err
		}
		val := el.Fields[1].Get()
		if val == nil {
			input[tag.String()].Val = ""
		} else {
			input[tag.String()].Val = val.(string)
		}
	}
	return nil
}

func (input I18nInput) Error() string {
	for _, inner := range input {
		if inner.Error != nil {
			return inner.Error.Error()
		}
	}
	return ""
}
