package internal

import (
	"context"
	"github.com/gogf/gf/util/guid"
	"gxt-file-server/app/agent"
	"gxt-file-server/app/errors"
	"gxt-file-server/app/model"
	"gxt-file-server/app/schema"
	"log"
)

// NewFileChunk 创建demo
func NewFileChunk(mFileChunk model.IFileChunk) *FileChunk {
	return &FileChunk{
		FileChunkModel: mFileChunk,
	}
}

// FileChunk 示例程序
type FileChunk struct {
	FileChunkModel model.IFileChunk
}

// Query 查询数据
func (a *FileChunk) Query(ctx context.Context, params schema.FileChunkQueryParam, opts ...schema.FileChunkQueryOptions) (*schema.FileChunkQueryResult, error) {
	return a.FileChunkModel.Query(ctx, params, opts...)
}

// Get 查询指定数据
func (a *FileChunk) Get(ctx context.Context, recordID string, opts ...schema.FileChunkQueryOptions) (*schema.FileChunk, error) {
	item, err := a.FileChunkModel.Get(ctx, recordID, opts...)
	if err != nil {
		return nil, err
	} else if item == nil {
		return nil, errors.ErrNotFound
	}
	return item, nil
}

func (a *FileChunk) getUpdate(ctx context.Context, recordID string) (*schema.FileChunk, error) {
	return a.Get(ctx, recordID)
}

// Create 创建数据
func (a *FileChunk) Create(ctx context.Context, item schema.FileChunk) (*schema.FileChunk, error) {
	item.RecordID = guid.S()
	err := a.FileChunkModel.Create(ctx, item)
	if err != nil {
		return nil, err
	}
	return a.getUpdate(ctx, item.RecordID)
}

// Update 更新数据
func (a *FileChunk) Update(ctx context.Context, recordID string, item schema.FileChunk) (*schema.FileChunk, error) {
	oldItem, err := a.FileChunkModel.Get(ctx, recordID)
	if err != nil {
		return nil, err
	} else if oldItem == nil {
		return nil, errors.ErrNotFound
	}
	err = a.FileChunkModel.Update(ctx, recordID, item)
	if err != nil {
		return nil, err
	}
	return a.getUpdate(ctx, recordID)
}

// Delete 删除数据
func (a *FileChunk) Delete(ctx context.Context, recordID string) error {
	oldItem, err := a.FileChunkModel.Get(ctx, recordID)
	if err != nil {
		return err
	} else if oldItem == nil {
		return errors.ErrNotFound
	}

	return a.FileChunkModel.Delete(ctx, recordID)
}

//ClearChunks 清理过期的文件分块
func (f *FileChunk) ClearChunks(ctx context.Context) error {
	results, err := f.FileChunkModel.Query(ctx, schema.FileChunkQueryParam{
		IsClear: true,
	})
	if err != nil {
		return err
	}
	log.Printf("共检测出%d块过期文件", len(results.Data))
	for _, v := range results.Data {
		//删除文件
		err = agent.DefaultAgent().RemoveObject(ctx, v.Path)
		if err != nil {
			return err
		}
		//删除数据
		err = f.FileChunkModel.Delete(ctx, v.RecordID)
		if err != nil {
			return err
		}
		log.Printf("删除文件:%v\n", v.Path)
	}
	return nil
}
