import {$, fetch, fs, glob, os, path, spinner, syncProcessCwd, usePowerShell} from 'zx'
import {isEqual, trim} from "licia";

syncProcessCwd(true)
if (isEqual(os.platform(), 'win32')) {
    usePowerShell()
}

const maven_setting = '/Users/lanyuanxiaoyao/.m2/settings-nas.xml'

const upload_url = 'http://132.126.207.124:36800'
const upload_username = 'AxhEbscwsJDbYMH2'
const upload_password = 'cYxg3b4PtWoVD5SjFayWxtnSVsjzRsg4'

const millisecondToString = (timestamp) => {
    const totalSeconds = Math.floor(parseFloat(timestamp) / 1000)
    if (isNaN(totalSeconds) || totalSeconds < 0) {
        return "0秒";
    }

    const days = Math.floor(totalSeconds / 86400)
    let remaining = totalSeconds % 86400
    const hours = Math.floor(remaining / 3600)
    remaining %= 3600
    const minutes = Math.floor(remaining / 60)
    const seconds = remaining % 60

    const parts = []
    if (days > 0) parts.push(`${days}天`)
    if (days > 0 || hours > 0) parts.push(`${hours}小时`)
    if (days > 0 || hours > 0 || minutes > 0) parts.push(`${minutes}分钟`)
    parts.push(`${seconds}秒`)

    return parts.join('')
}

export const run_deploy = async (project) => {
    let output = await spinner(
        `Deploying project ${project}`,
        () => $`mvn -pl ${project} clean deploy -D skipTests -s ${maven_setting}`
    )
    console.log(`✅  Finish deploy ${project} (${millisecondToString(output['duration'])})`)
}

export const run_deploy_root = async () => {
    let output = await spinner(
        `Deploying root`,
        () => $`mvn clean deploy -N -D skipTests -s ${maven_setting}`
    )
    console.log(`✅  Finish deploy root (${millisecondToString(output['duration'])})`)
}

export const run_deploy_batch = async (projects) => {
    for (const project of projects) {
        await run_deploy(project)
    }
}

export const run_package = async (project, profile = 'b2b12') => {
    let output = await spinner(
        `Packaging project ${project}${isEqual(profile, 'b2b12') ? '' : ` ${profile}`}`,
        () => $`mvn -pl ${project} clean package -D skipTests -P ${profile} -s ${maven_setting}`
    )
    console.log(`✅  Finish package ${project}${isEqual(profile, 'b2b12') ? '' : ` ${profile}`} (${millisecondToString(output['duration'])})`)
}

export const run_package_batch = async (projects) => {
    for (const project of projects) {
        await run_package(project)
    }
}

const upload = async (file_path) => {
    let start = new Date().getTime()
    let response = await spinner(
        `Uploading project ${file_path}`,
        () => fetch(`${upload_url}/file/upload/${path.basename(file_path)}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/octet-stream',
                'Authorization': `Basic ${Buffer.from(`${upload_username}:${upload_password}`).toString('base64')}`,
            },
            body: fs.createReadStream(file_path),
            duplex: 'half',
        })
    )

    if (!isEqual(response.status, 200)) {
        throw response
    }
    console.log(`✅  Finish upload ${file_path} (${millisecondToString((new Date().getTime()) - start)})`)
    fs.rmSync(file_path)
}

export const run_upload = async (pattern) => {
    for (let p of glob.sync(pattern)) {
        await upload(path.join(trim($.sync`pwd`.text()), p))
    }
}

export const run_upload_normal = async (project) => {
    await run_upload(`${project}/target/${project}-1.0.0-SNAPSHOT.jar`)
}
