import Env from '@ioc:Adonis/Core/Env'
import BaseSeeder from '@ioc:Adonis/Lucid/Seeder'
import Drive from '@ioc:Adonis/Core/Drive'
import * as fs from 'fs'
import * as path from 'path'
import OSS from 'ali-oss'
export default class extends BaseSeeder {
    public async run() {
        // Write your database queries inside the run method
        // const dir = '/Volumes/Data HD/shortplay/files/08F2CNhR'
        // await Promise.all(
        //     fs
        //         .readdirSync(dir)
        //         .map((file) =>
        //             Drive.putStream(
        //                 path.join('files/08F2CNhR', file),
        //                 fs.createReadStream(path.join(dir, file))
        //             )
        //         )
        // )
        const client = new OSS({
            // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
            region: Env.get('OSS_REGION'),
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            accessKeyId: Env.get('OSS_KEY'),
            accessKeySecret: Env.get('OSS_SECRET'),
            // 填写Bucket名称。
            bucket: Env.get('OSS_BUCKET')
        })
        // const dirs = await client.listV2({
        //     prefix: 'files/asdf',
        //     delimiter: '/'
        // })
        // console.log(dirs)
        const downloaded = '/Volumes/Data HD/shortplay/downloaded'
        const dir = '/Volumes/Data HD/shortplay/files'
        const subDirs = fs
            .readdirSync(downloaded)
            .filter((file) => {
                const stat = fs.statSync(path.join(downloaded, file))
                return !stat.isDirectory() && !/^\./.test(file)
            })
            .sort()
            .map((file) => {
                return file.replace('.json', '')
            })
        for (let i = 0; i < 10; i++) {
            const subDir = subDirs[i]
            const files = fs.readdirSync(path.join(dir, subDir)).filter((file) => {
                const stat = fs.statSync(path.join(dir, subDir, file))
                return !stat.isDirectory()
            })
            const cover = files.find((file) => /^cover_/.test(file))

            if (cover) {
                const key = path.join('files', subDir, cover)
                try {
                    await client.head(key)
                    await client.putACL(key, 'public-read')
                    console.log('exists', key)
                } catch (error) {}
            }
        }
    }
}
