package xml_loader

import (
	"encoding/xml"
	"fmt"

	"gitea.urkob.com/urko/ess-etl-go/internal/request"
	"gitea.urkob.com/urko/ess-etl-go/pkg/domain"
	"github.com/docker/go-units"
)

type EmployeeWILoader struct {
	r request.RequestService
}

func NewEmployeeWILoader(r request.RequestService) EmployeeWILoader {
	return EmployeeWILoader{r: r}
}

func (e EmployeeWILoader) LoadEmployeeList(employeeIDList []string, from, to string) ([]domain.EmployeeWorkInformation, error) {
	xmlBts := make([]byte, 0, units.MiB*5)
	err := e.r.EmployeeWorkInformation(&xmlBts, employeeIDList, from, to)
	if err != nil {
		return nil, fmt.Errorf("r.EmployeeWorkInformation: %s", err)
	}
	if len(xmlBts) <= 0 {
		return nil, fmt.Errorf("couldn't load xml ")
	}

	return loadFromXML(xmlBts)
}

func (e EmployeeWILoader) LoadEmployee(employeeID, from, to string) ([]domain.EmployeeWorkInformation, error) {
	employeeIDList := []string{employeeID}
	xmlBts := make([]byte, 0, units.MiB*5)
	err := e.r.EmployeeWorkInformation(&xmlBts, employeeIDList, from, to)
	if err != nil {
		return nil, fmt.Errorf("r.EmployeeWorkInformation: %s", err)
	}
	if len(xmlBts) <= 0 {
		return nil, fmt.Errorf("couldn't load xml ")
	}
	return loadFromXML(xmlBts)
}

func loadFromXML(xmlFile []byte) ([]domain.EmployeeWorkInformation, error) {
	var awi domain.ArrayOfEmployeeWorkInformation
	if err := xml.Unmarshal(xmlFile, &awi); err != nil {
		return nil, fmt.Errorf("xml.Unmarshal: %s", err)
	}
	return awi.EmployeeWorkInfos, nil
}

func (e EmployeeWILoader) GoLoadEmployee(employeeID, from, to string) ([]byte, error) {
	employeeIDList := []string{employeeID}
	xmlBts := make([]byte, 0, units.MiB*5)
	err := e.r.EmployeeWorkInformation(&xmlBts, employeeIDList, from, to)
	if err != nil {
		return nil, fmt.Errorf("r.EmployeeWorkInformation: %s", err)
	}
	if len(xmlBts) <= 0 {
		return nil, fmt.Errorf("couldn't load xml ")
	}
	return xmlBts, nil
}

func GoLoadFromXML(xmlFile []byte) ([]domain.EmployeeWorkInformation, error) {
	var awi domain.ArrayOfEmployeeWorkInformation
	if err := xml.Unmarshal(xmlFile, &awi); err != nil {
		return nil, fmt.Errorf("xml.Unmarshal: %s", err)
	}
	return awi.EmployeeWorkInfos, nil
}