package service

import (
	"context"
	"github.com/gofiber/fiber/v2"
	"github.com/minio/minio-go/v7"
	"github.com/rs/zerolog"
	"go-humas-be/app/module/ppid_data_categories/mapper"
	"go-humas-be/app/module/ppid_data_categories/repository"
	"go-humas-be/app/module/ppid_data_categories/request"
	"go-humas-be/app/module/ppid_data_categories/response"
	minioStorage "go-humas-be/config/config"
	"go-humas-be/utils/paginator"
	"io"
	"log"
	"math/rand"
	"mime"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// PpidDataCategoriesService
type ppidDataCategoriesService struct {
	Repo         repository.PpidDataCategoriesRepository
	MinioStorage *minioStorage.MinioStorage
	Log          zerolog.Logger
}

// PpidDataCategoriesService define interface of IPpidDataCategoriesService
type PpidDataCategoriesService interface {
	All(req request.PpidDataCategoriesQueryRequest) (ppidDataCategories []*response.PpidDataCategoriesResponse, paging paginator.Pagination, err error)
	Show(id uint) (ppidDataCategories *response.PpidDataCategoriesResponse, err error)
	Save(req request.PpidDataCategoriesCreateRequest) (err error)
	SaveThumbnail(c *fiber.Ctx) (err error)
	Update(id uint, req request.PpidDataCategoriesUpdateRequest) (err error)
	Delete(id uint) error
	Viewer(c *fiber.Ctx) error
}

// NewPpidDataCategoriesService init PpidDataCategoriesService
func NewPpidDataCategoriesService(repo repository.PpidDataCategoriesRepository, minioStorage *minioStorage.MinioStorage, log zerolog.Logger) PpidDataCategoriesService {

	return &ppidDataCategoriesService{
		Repo:         repo,
		MinioStorage: minioStorage,
		Log:          log,
	}
}

// All implement interface of PpidDataCategoriesService
func (_i *ppidDataCategoriesService) All(req request.PpidDataCategoriesQueryRequest) (ppidDataCategoriess []*response.PpidDataCategoriesResponse, paging paginator.Pagination, err error) {
	results, paging, err := _i.Repo.GetAll(req)
	if err != nil {
		return
	}

	for _, result := range results {
		ppidDataCategoriess = append(ppidDataCategoriess, mapper.PpidDataCategoriesResponseMapper(result))
	}

	return
}

func (_i *ppidDataCategoriesService) Show(id uint) (ppidDataCategories *response.PpidDataCategoriesResponse, err error) {
	result, err := _i.Repo.FindOne(id)
	if err != nil {
		return nil, err
	}

	return mapper.PpidDataCategoriesResponseMapper(result), nil
}

func (_i *ppidDataCategoriesService) Save(req request.PpidDataCategoriesCreateRequest) (err error) {
	_i.Log.Info().Interface("data", req).Msg("")

	return _i.Repo.Create(req.ToEntity())
}

func (_i *ppidDataCategoriesService) SaveThumbnail(c *fiber.Ctx) (err error) {

	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	if err != nil {
		return err
	}

	_i.Log.Info().Str("timestamp", time.Now().
		Format(time.RFC3339)).Str("Service:SaveThumbnail", "Categories:SaveThumbnail").
		Interface("id", id).Msg("")

	bucketName := _i.MinioStorage.Cfg.ObjectStorage.MinioStorage.BucketName

	form, err := c.MultipartForm()
	if err != nil {
		return err
	}
	files := form.File["files"]

	// Create minio connection.
	minioClient, err := _i.MinioStorage.ConnectMinio()
	if err != nil {
		// Return status 500 and minio connection error.
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": true,
			"msg":   err.Error(),
		})
	}

	// Iterasi semua file yang diunggah
	for _, file := range files {

		_i.Log.Info().Str("timestamp", time.Now().
			Format(time.RFC3339)).Str("Service:Resource", "Uploader:: loop1").
			Interface("data", file).Msg("")

		src, err := file.Open()
		if err != nil {
			return err
		}
		defer src.Close()

		filename := filepath.Base(file.Filename)
		filenameWithoutExt := filepath.Clean(filename[:len(filename)-len(filepath.Ext(filename))])
		extension := filepath.Ext(file.Filename)[1:]

		rand.New(rand.NewSource(time.Now().UnixNano()))
		randUniqueId := rand.Intn(1000000)

		newFilenameWithoutExt := filenameWithoutExt + "_" + strconv.Itoa(randUniqueId)
		newFilename := newFilenameWithoutExt + "." + extension
		objectName := "ppid/category/thumbnail/" + newFilename

		findCategory, err := _i.Repo.FindOne(uint(id))
		findCategory.ThumbnailPath = &objectName
		err = _i.Repo.Update(uint(id), findCategory)
		if err != nil {
			return err
		}

		// Upload file ke MinIO
		_, err = minioClient.PutObject(context.Background(), bucketName, objectName, src, file.Size, minio.PutObjectOptions{})
		if err != nil {
			return err
		}
	}

	_i.Log.Info().Str("timestamp", time.Now().
		Format(time.RFC3339)).Str("Service:Resource", "User:All").
		Interface("data", "Successfully uploaded").Msg("")

	return
}

func (_i *ppidDataCategoriesService) Update(id uint, req request.PpidDataCategoriesUpdateRequest) (err error) {
	_i.Log.Info().Interface("data", req).Msg("")
	return _i.Repo.Update(id, req.ToEntity())
}

func (_i *ppidDataCategoriesService) Delete(id uint) error {
	result, err := _i.Repo.FindOne(id)
	if err != nil {
		return err
	}

	isActive := false
	result.IsActive = &isActive
	return _i.Repo.Update(id, result)
}

func (_i *ppidDataCategoriesService) Viewer(c *fiber.Ctx) (err error) {
	id, err := strconv.ParseUint(c.Params("id"), 10, 0)
	result, err := _i.Repo.FindOne(uint(id))
	if err != nil {
		return err
	}

	if result.ThumbnailPath == nil {
		return nil
	}

	ctx := context.Background()
	bucketName := _i.MinioStorage.Cfg.ObjectStorage.MinioStorage.BucketName
	objectName := result.ThumbnailPath

	_i.Log.Info().Str("timestamp", time.Now().
		Format(time.RFC3339)).Str("Service:Resource", "Article:Uploads").
		Interface("data", objectName).Msg("")

	// Create minio connection.
	minioClient, err := _i.MinioStorage.ConnectMinio()
	if err != nil {
		// Return status 500 and minio connection error.
		return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
			"error": true,
			"msg":   err.Error(),
		})
	}

	fileContent, err := minioClient.GetObject(ctx, bucketName, *objectName, minio.GetObjectOptions{})
	if err != nil {
		log.Fatalln(err)
	}
	defer fileContent.Close()

	contentType := mime.TypeByExtension("." + getFileExtension(*objectName))
	if contentType == "" {
		contentType = "application/octet-stream"
	}

	c.Set("Content-Type", contentType)

	if _, err := io.Copy(c.Response().BodyWriter(), fileContent); err != nil {
		return err
	}

	return
}

func getFileExtension(filename string) string {
	// split file name
	parts := strings.Split(filename, ".")

	// jika tidak ada ekstensi, kembalikan string kosong
	if len(parts) == 1 || (len(parts) == 2 && parts[0] == "") {
		return ""
	}

	// ambil ekstensi terakhir
	return parts[len(parts)-1]
}
