import { Injectable, Logger } from '@nestjs/common'
import { AliyunService } from '../aliyun/aliyun.service'
import * as randomstring from 'randomstring'
import { format } from 'date-fns'

@Injectable()
export class FileService {
    constructor(private readonly aliyunService: AliyunService) {}

    public async upload(file: Express.Multer.File) {
        const { originalname, buffer, mimetype } = file
        let path = 'file/'
        if (mimetype) {
            path = mimetype.split('/')[0] + '/'
        }
        path +=
            format(new Date(), 'yyyyMMdd/') +
            randomstring.generate({ length: 8, charset: 'alphanumeric' }).toLowerCase() +
            this.getFileExt(originalname)
        Logger.log(`upload file name=${originalname} type=${mimetype}`)
        const result = await this.aliyunService.uploadFile(path, buffer)
        return result
    }

    public async uploadBuffer(buffer: Buffer, type, ext) {
        let path = `file/${type}/`
        path +=
            format(new Date(), 'yyyyMMdd/') +
            randomstring.generate({ length: 8, charset: 'alphanumeric' }).toLowerCase() +
            '.' +
            ext
        const result = await this.aliyunService.uploadFile(path, buffer)
        return result
    }

    public getFileExt(filename: string) {
        const index = filename.lastIndexOf('.')
        if (index === -1) {
            return ''
        }
        return filename.substring(index)
    }
}
