const { LogType } = require("loguix")
const fs = require("fs")
const path = require("path")
const { __glob } = require("./global-variables")
const clog = new LogType("Pïpeline")
const config = require("./config")

const tokenkey = config.getFile().JENKINS_TOKEN

module.exports.getAllPipelines = function() {

    return new Promise((resolve, reject) => {
       
        
        fetch(`https://jenkins.raphix.fr/api/json`, {
            method: "GET",
            headers: {
                "Accept": "application/json",
                "Authorization": `Basic ${tokenkey}`
            },
            credentials: "include"
        })
        .then(res => res.json())
        .then(async list  => {

            const pipelinesJobs = new Array()

            for(const job of list.jobs) {
                    await fetch(`${job.url}/api/json`, {
                    method: "GET",
                    headers: {
                        "Accept": "application/json",
                        "Authorization": `Basic ${tokenkey}`
                    },
                    credentials: "include"
                    })
                    .then(res => res.json())
                    .then(async res => {

                       if(res._class == "org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject") {
                            await getJobMain(res).then(resJ => {
                                res.jobs[0] = resJ
                                pipelinesJobs.push(res)
                            })
                       } else {
                            pipelinesJobs.push(res)

                       }

                 
                    })
            }

            list.jobs = pipelinesJobs

            resolve(list)

           
        })
        .catch(err => {
            resolve("UNAVAILABLE")
        })
    })

    
}

module.exports.startPipeline = function(pipeline) {

    
// If it's a freestyle job, build with params

    if(pipeline.type == "org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject") {
        return new Promise((resolve, reject) => {
            fetch(`${pipeline.url}/job/${pipeline.jobname}/build?delay=0sec`, {
                method: "POST",
                headers: {
                    "Authorization": `Basic ${tokenkey}`
                },
                credentials: "include"
            })
            .then(res => {
                resolve("OK")
            })
        })
    } else {
        return new Promise((resolve, reject) => {

            const parameters = pipeline.fields

            const formatedParams = new URLSearchParams()

            for(const param of parameters) {
                formatedParams.append(param.name, param.value)
            }
         
          


            fetch(`${pipeline.url}/buildWithParameters?delay=0sec`, {
                method: "POST",
                headers: {
                    "Authorization": `Basic ${tokenkey}`,
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                credentials: "include",
                body: formatedParams
            })
            .then(res => {
                resolve("OK")
            })
        })
    }


    
}

function getJobMain(res) {

    return new Promise(async (resolve,  reject) => {
        
        await fetch(`${res.jobs[0].url}/api/json`, {
            method: "GET",
            headers: {
                'Accept': 'application/json',
                'Authorization': `Basic ${tokenkey}`
            },
            credentials: 'include'
        }).then(res => res.json())
        .then(res => {
            resolve(res)
        })

       
    })
        
}
