package dev_services

import (
	"cpone/db"
	"cpone/models"
	dbx "cpone/package/database"
	"fmt"
	"math"
	"strings"
)

func NewMDSampleStationServices(uStore db.AppStore) *MDSampleStationServices {
	return &MDSampleStationServices{
		MDSampleStationStore: uStore,
	}
}

type MDSampleStationServices struct {
	MDSampleStationStore db.AppStore
}

func (ss *MDSampleStationServices) GetMDSampleStationBreadcrumb() (models.BreadCrumbV1, error) {
	var ret models.BreadCrumbV1

	Breadcrumb := models.BreadCrumbV1{
		Title: "Master Sample Station",
		Item: []models.ItemBreadCrumbV1{
			{
				Item: "Dashboard",
				Url:  "/dev/dashboard",
			},
			{
				Item: "Master",
				Url:  "/dev/master",
			},
			{
				Item: "Sample Stasion",
				Url:  "",
			},
		},
	}

	ret = Breadcrumb
	return ret, nil
}

func (ss *MDSampleStationServices) GetListSampleStation(search string, currentPage int, rowPerPage int) ([]models.MDSampleStation, int, error) {
	var sampleStationList []models.MDSampleStation
	var totalData int

	offset := (currentPage - 1) * rowPerPage
	prm := "%" + strings.TrimSpace(search) + "%"
	querytotal := `
	SELECT COUNT(*)
	FROM t_samplestation 
	WHERE T_SampleStationIsActive = 'Y' AND (T_SampleStationCode LIKE ? OR T_SampleStationName LIKE ?)
	`
	if err := dbx.Handlex.Get(&totalData, querytotal, prm, prm); err != nil {
		return nil, 0, fmt.Errorf("error query get total data: %v", err)
	}

	query := `
	SELECT
	T_SampleStationID,
	T_SampleStationCode,
	T_SampleStationName,
	T_SampleStationNat_GroupID,
	T_SampleStationIsNonLab,
	T_SampleStationIsActive
	FROM t_samplestation
	WHERE T_SampleStationIsActive = 'Y'
	AND (T_SampleStationCode LIKE ? OR T_SampleStationName LIKE ?)
	ORDER BY T_SampleStationID ASC
	LIMIT ? OFFSET ?
	`
	if err := dbx.Handlex.Select(&sampleStationList, query, prm, prm, rowPerPage, offset); err != nil {
		return nil, 0, fmt.Errorf("error query database: %v", err)
	}
	totalPage := int(math.Ceil(float64(totalData) / float64(rowPerPage)))

	for _, d := range sampleStationList {
		if len(d.T_SampleStationIsNonLab) == 0 {
			d.T_SampleStationIsNonLab = "Lab"
		}
	}

	return sampleStationList, totalPage, nil
}
