import {PDFDocument, StandardFonts, rgb} from "pdf-lib"
import dayjs from "dayjs"


const getCoordinatesForPDFLib = (x ,y, page) => {
    /*
    * @param x the wanted X Parameter in Millimeters from Top Left
    * @param y the wanted Y Parameter in Millimeters from Top Left
    * @param page the page Object
    *
    * @returns x,y object
    * */


    let retX = x * 2.83
    let retY = page.getHeight()-(y*2.83)

    return {
        x: retX,
        y: retY
    }

}

const getDuration = (time) => {
    const minutes = Math.floor(dayjs(time.endDate).diff(dayjs(time.startDate),'minutes',true))
    const hours = Math.floor(minutes/60)
    return {
        //dezimal: dez,
        hours: hours,
        minutes: minutes,
        composed: `${hours}:${String(minutes % 60).padStart(2,"0")} Std`
    }
}




export const useCreateWorkingTimesPdf = async (input,backgroundSourceBuffer) => {

    const uri = ref("test")
    const genPDF = async () => {
        const pdfDoc = await PDFDocument.create()

        const font = await pdfDoc.embedFont(StandardFonts.Helvetica)
        const fontBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold)

        let pages = []
        let pageCounter = 1



        const backgroudPdf = await PDFDocument.load(backgroundSourceBuffer)

        const firstPageBackground = await pdfDoc.embedPage(backgroudPdf.getPages()[0])
        const secondPageBackground = await pdfDoc.embedPage(backgroudPdf.getPages()[backgroudPdf.getPages().length > 1 ? 1 : 0])

        const page1 = pdfDoc.addPage()

        page1.drawPage(firstPageBackground, {
            x: 0,
            y: 0,
        })

        pages.push(page1)


        //Falzmarke 1
        /*pages[pageCounter - 1].drawLine({
            start: getCoordinatesForPDFLib(0,105,page1),
            end: getCoordinatesForPDFLib(7,105,page1),
            thickness: 0.25,
            color: rgb(0,0,0),
            opacity: 1
        })*/

        //Lochmarke
        /*pages[pageCounter - 1].drawLine({
            start: getCoordinatesForPDFLib(0,148.5,page1),
            end: getCoordinatesForPDFLib(7,148.5,page1),
            thickness: 0.25,
            color: rgb(0,0,0),
            opacity: 1
        })*/

        //Falzmarke 2
        /*pages[pageCounter - 1].drawLine({
            start: getCoordinatesForPDFLib(0,210,page1),
            end: getCoordinatesForPDFLib(7,210,page1),
            thickness: 0.25,
            color: rgb(0,0,0),
            opacity: 1
        })*/
        console.log(input)
        pages[pageCounter - 1].drawText(`Mitarbeiter: ${input.profile}`,{
            x: getCoordinatesForPDFLib(20,65,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,65,pages[pageCounter -1]).y,
            size: 10,
        })
        pages[pageCounter - 1].drawText(`Eingereicht: ${Math.floor(input.sumWorkingMinutesEingereicht/60)}:${String(input.sumWorkingMinutesEingereicht % 60).padStart(2,"0")} Std`,{
            x: getCoordinatesForPDFLib(20,70,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,70,pages[pageCounter -1]).y,
            size: 10,
        })
        pages[pageCounter - 1].drawText(`Genehmigt: ${Math.floor(input.sumWorkingMinutesApproved/60)}:${String(input.sumWorkingMinutesApproved % 60).padStart(2,"0")} Std`,{
            x: getCoordinatesForPDFLib(20,75,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,75,pages[pageCounter -1]).y,
            size: 10,
        })

        pages[pageCounter - 1].drawText(`Feiertagsausgleich: ${Math.floor(input.sumWorkingMinutesRecreationDays/60)}:${String(input.sumWorkingMinutesRecreationDays % 60).padStart(2,"0")} Std`,{
            x: getCoordinatesForPDFLib(20,80,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,80,pages[pageCounter -1]).y,
            size: 10,
        })
        pages[pageCounter - 1].drawText(`Urlaubsausgleich: ${Math.floor(input.sumWorkingMinutesVacationDays/60)}:${String(input.sumWorkingMinutesVacationDays % 60).padStart(2,"0")} Std`,{
            x: getCoordinatesForPDFLib(20,85,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,85,pages[pageCounter -1]).y,
            size: 10,
        })
        pages[pageCounter - 1].drawText(`Krankheitsausgleich: ${Math.floor(input.sumWorkingMinutesSickDays/60)}:${String(input.sumWorkingMinutesSickDays % 60).padStart(2,"0")} Std`,{
            x: getCoordinatesForPDFLib(20,90,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,90,pages[pageCounter -1]).y,
            size: 10,
        })
        pages[pageCounter - 1].drawText(`Soll Stunden: ${Math.floor(input.timeSpanWorkingMinutes/60)}:${String(input.timeSpanWorkingMinutes % 60).padStart(2,"0")} Std`,{
            x: getCoordinatesForPDFLib(20,95,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,95,pages[pageCounter -1]).y,
            size: 10,
        })
        pages[pageCounter - 1].drawText(`Inoffizielles Saldo: ${Math.sign(input.saldoInOfficial) === 1 ? "+" : "-"} ${Math.floor(Math.abs(input.saldoInOfficial/60))}:${String(Math.abs(input.saldoInOfficial)  % 60).padStart(2,"0")} Std`,{
            x: getCoordinatesForPDFLib(20,100,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,100,pages[pageCounter -1]).y,
            size: 10,
        })
        pages[pageCounter - 1].drawText(`Saldo: ${Math.sign(input.saldo) === 1 ? "+" : "-"} ${Math.floor(Math.abs(input.saldo/60))}:${String(Math.abs(input.saldo)  % 60).padStart(2,"0")} Std`,{
            x: getCoordinatesForPDFLib(20,105,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,105,pages[pageCounter -1]).y,
            size: 10,
        })

        pages[pageCounter - 1].drawText(`Start:`,{
            x: getCoordinatesForPDFLib(20,110,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(20,110,pages[pageCounter -1]).y,
            size: 10,
        })

        pages[pageCounter - 1].drawText(`Ende:`,{
            x: getCoordinatesForPDFLib(60,110,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(60,110,pages[pageCounter -1]).y,
            size: 10,
        })

        pages[pageCounter - 1].drawText(`Dauer:`,{
            x: getCoordinatesForPDFLib(100,110,pages[pageCounter -1]).x,
            y: getCoordinatesForPDFLib(100,110,pages[pageCounter -1]).y,
            size: 10,
        })


        let rowHeight = 115


        let splitted = []

        let reversedInput = input.times.slice().reverse()

        const splittedLength = Math.floor((reversedInput.length - 25) / 40)

        splitted.push(reversedInput.slice(0,25))

        let lastIndex = 25
        for (let i = 0; i < splittedLength; ++i ) {
            splitted.push(reversedInput.slice(lastIndex, lastIndex + (i + 1) * 40))
            lastIndex = lastIndex + (i + 1) * 40 + 1
        }

        splitted.push(reversedInput.slice(lastIndex, reversedInput.length))


        splitted.forEach((chunk,index) => {
            if(index > 0) {
                const page = pdfDoc.addPage()

                page.drawPage(secondPageBackground, {
                    x: 0,
                    y: 0,
                })

                pages.push(page)
                pageCounter++
                rowHeight = 20

            }

            chunk.forEach(time => {
                pages[pageCounter - 1].drawText(`${dayjs(time.startDate).format("HH:mm DD.MM.YY")}`,{
                    x: getCoordinatesForPDFLib(20,rowHeight,pages[pageCounter -1]).x,
                    y: getCoordinatesForPDFLib(20,rowHeight,pages[pageCounter -1]).y,
                    size: 10,
                })

                pages[pageCounter - 1].drawText(`${dayjs(time.endDate).format("HH:mm DD.MM.YY")}`,{
                    x: getCoordinatesForPDFLib(60,rowHeight,pages[pageCounter -1]).x,
                    y: getCoordinatesForPDFLib(60,rowHeight,pages[pageCounter -1]).y,
                    size: 10,
                })

                pages[pageCounter - 1].drawText(`${getDuration(time).composed}`,{
                    x: getCoordinatesForPDFLib(100,rowHeight,pages[pageCounter -1]).x,
                    y: getCoordinatesForPDFLib(100,rowHeight,pages[pageCounter -1]).y,
                    size: 10,
                })

                rowHeight += 6

            })
        })




        uri.value = await pdfDoc.saveAsBase64({dataUri: true})

    }

    await genPDF()

    return uri.value


}