const path = require('path')

let writeError = 0
let user_count = 0
let appLoc = path.join(..._program.split('services')[0].split('/'))
const sessionStoragePath = path.resolve(__dirname, '..', '..', 'drive', 'files', appLoc, 'mock-storage')

if (!fs.existsSync(sessionStoragePath)){
    fs.mkdirSync(sessionStoragePath);
}

let jsDataFileText = ''

if (_WEBIN_FILENAME1.includes('jsdata')) jsDataFileText = _WEBIN_FILEREF1.toString()
if (_WEBIN_FILENAME2.includes('jsdata')) jsDataFileText = _WEBIN_FILEREF2.toString()

if (jsDataFileText.length > 0) {
    if (jsDataFileText.includes('USER_ID')) {
        user_count = jsDataFileText.split('\n').length - 1

        const usersStore = path.resolve(sessionStoragePath, 'users.json')
        let isRegistered = 1

        if (jsDataFileText.includes('notregistered')) {
            isRegistered = 0
        }

        const json = {
            REGISTERCOUNT: user_count,
            ISREGISTERED: isRegistered
        }

        try {
            fs.writeFileSync(usersStore, JSON.stringify(json))
        } catch (err) {
            writeError = 1
        }
    }
} else {
    console.log('Error reading jsdata input')
}

_webout = `{"SYSDATE" : "26SEP22"
,"SYSTIME" : "08:43"
, "sasparams":
[
{
"USER_COUNT": "${user_count}",
"STATUS": "${writeError === 0 ? 'SUCCESS' : 'ERROR WRITING'}",
"DSID": "DC20220926T084322234_729360_2744",
"URL": "http://SAS.demo.sas.com:80/SASStoredProcess?_program=/Projects/app/dc/services/editors/getlog&table=DC20220926T084322234_729360_2744"
}
]
,"_DEBUG" : ""
,"_METAUSER": "sasdemo@SAS"
,"_METAPERSON": "sasdemo"
,"_PROGRAM" : "/Projects/app/dc/services/editors/stagedata"
,"AUTOEXEC" : "D%3A%5Copt%5Csasinside%5CConfig%5CLev1%5CSASApp%5CStoredProcessServer%5Cautoexec.sas"
,"MF_GETUSER" : "sasdemo"
,"SYSCC" : "0"
,"SYSENCODING" : "wlatin1"
,"SYSERRORTEXT" : ""
,"SYSHOSTNAME" : "SAS"
,"SYSPROCESSID" : "41DD80576A63958140A31C0000000000"
,"SYSPROCESSMODE" : "SAS Stored Process Server"
,"SYSPROCESSNAME" : ""
,"SYSJOBID" : "27448"
,"SYSSCPL" : "Linunx"
,"SYSSITE" : "123"
,"SYSUSERID" : "sassrv"
,"SYSVLONG" : "9.04.01M7P080520"
,"SYSWARNINGTEXT" : "ENCODING option ignored for files opened with RECFM=N."
,"END_DTTM" : "2022-09-26T08:43:24.624000"
,"MEMSIZE" : "46GB"
}
`