const { dateTime, secondsFormat, getPastDateTimeFromSeconds, currentYearMonthDay } = require('./dateTime')
const requestConfigHeader = require('./requestConfigHeader')
const flatten = require('flat')
const unflatten = require('flat').unflatten
const axios = require('axios')
const path = require('path')
const convertToIntegerIfNumber = require('./convertToIntegerIfNumber')
const sendMessageSocket = require('./sendMessageSocket')

async function journalingRequest(request, body, crmCallDuration, contact, crmAgent, crmPhone, authentication, test = {}) {
    const { requestContentType, requestEncoding, requestType, responseType, url } = request

    console.log('----------> crmCallDuration: ', crmCallDuration)
    console.log('----------> url: ', url)

    body = flatten(body)

    let ignore = []

    for (let key in body) {

        const k = Object.keys(body).find(k => {
            if (!ignore.includes(k) && k.includes('._prop') && k.replace('._prop', '._type') ==
                key.replace('._prop', '._type')) {
                ignore.push(key)
                return true
            }
        }
        )

        if (k) {
            const type = body[k.replace('._prop', '._type')]
            const format = body[k.replace('._prop', '._format')]

            const newKey = k.replace('._prop', '').replace('._type', '').replace('._format', '')

            if (body[key] == 'crmCallDuration') {
                switch (format) {
                    case 'hh:mm':
                        body[newKey] = secondsFormat(crmCallDuration, 'hh:mm')
                        break
                    case 'milliseconds':
                        body[newKey] = secondsFormat(crmCallDuration, 'milliseconds')
                        break
                    case 'seconds':
                        body[newKey] = secondsFormat(crmCallDuration, 'seconds')
                        break
                }
            }
            else if (body[key] == 'crmCallDateTime') {
                switch (format) {
                    case 'ISO8601':
                        body[newKey] = crmCallDuration ? getPastDateTimeFromSeconds(dateTime(), crmCallDuration) : dateTime()
                        break
                }
            }
            else if (body[key] == 'crmContactId') {
                body[newKey] = contact.contactId
            }
            else if (body[key] == 'crmAgent') {
                body[newKey] = crmAgent
            }
            else if (body[key] == 'crmPhone') {
                body[newKey] = crmPhone
            }

            const property = body[newKey] ? body[newKey] : body[key]

            switch (type) {
                case 'number':
                    body[newKey] = convertToIntegerIfNumber(property)
                    break
                case 'string':
                    body[newKey] = `${property}`
                    break
                case 'boolean':
                    body[newKey] = Boolean(property)
                    break
            }
            continue
        }

        switch (body[key]) {
            case 'crmPhone':
                body[key] = crmPhone
                break
            case 'crmContactId':
                body[key] = contact.contactId
                break
            case 'crmAgent':
                body[key] = crmAgent
                break
            case 'crmCallDuration':
                body[key] = crmCallDuration
                break
            case 'YYYY-MM-DD':
                body[key] = currentYearMonthDay()
                break
        }

    }

    const data = unflatten(body)


    // Refactor this. Some times the crmCallDuration is comming with the value like 'crmCallDuration' instead of number when 
    // creating call journaling for salesforce
    // if (url.includes('salesforce')) {
    //     for (let key in data) {
    //         if (data[key] == 'crmCallDuration') {
    //             data[key] = 300
    //         }
    //     }
    // }


    const { type, userName, passWord, token, crmClientId } = authentication

    const config = await requestConfigHeader(url, crmPhone, requestType, requestContentType, type, userName, passWord, token, crmClientId, data)

    if (test?.testing && test?.companyId && test?.msg) {
        sendMessageSocket({ companyId: test.companyId, status: 'processing', data: { request: config, msg: test.msg } })
    }

    console.log('#####################')
    console.log('CONFIG CALL JOURNALING: ', JSON.stringify(config, null, 6))
    console.log('#####################')

    try {
        const res = await axios(config)
    } catch (error) {
        console.log(`CALL JOURNALING ERROR: `, error)
    }


}

module.exports = journalingRequest