--vasriable to make it only generate the ini on first run
local run = true
--make the script file to be written to
local reader = getFileReader("DakiScript/DakiScript.ini", false)
if not reader then 
    local writer = getFileWriter("DakiScript/DakiScript.ini", true, false)
    writer:write(DakiData.Comments)
    writer:close()
    run = false -- set false to make it only run this on first go
end

local filePath = "" --tracks the filepath as it moves in string format
local modName  
local modPath = ""
local mangaType
local dakiType
local massDaki = {}
local massManga = {}
local modInfotxt
local makeWhat = "daki"
local doMangaIcons = false
local doDakiIcons = false
local toolTips = {}
local scripts = {}
toolTips.daki = {}
toolTips.manga = {}
scripts.armorScript =""
scripts.modelScript =""
scripts.itemScript =""
scripts.armorRecipe =""
scripts.mangaScript=""
scripts.mangaModels=""


--check if icons is true


local function CheckDaki(type)
        local type = string.upper(type)
        if string.find(type,"DAKI") or string.find(type,"PILLOW") then
            return true
        end
        return false
end
local function CheckManga(type)
    local type = string.upper(type)
    if string.find(type,"MANGA") or string.find(type,"COMIC") then
        return true
    end
    return false
end

local function CompileDakiScripts(type,name,texture,icon,itemid)
    if CheckDaki(type) then
        local iconArmor
        local toolTip
        if toolTips.daki[name] then
            toolTip = "Tooltip_"..name
        else toolTip = ""
        end
        if icon then icon = "daki"..itemid
        iconArmor = "dakiArmor" .. itemid
        else icon = "Dakimakura"
         iconArmor = icon.."Armor"end
        local moduleName = string.gsub(modName, "%s+", "")
        local flipscript = string.format(DakiData.DakiScript.items,itemid .. "Flip",name,moduleName,itemid .. "Flip",icon,itemid .. "Flip",toolTip)
        local itemScript = string.format(DakiData.DakiScript.items,itemid,name,moduleName,itemid,icon,itemid,toolTip)
        scripts.itemScript =  scripts.itemScript  .. itemScript .. flipscript
        scripts.armorScript = scripts.armorScript .. string.format(DakiData.DakiScript.armorItems,itemid,name,moduleName,itemid,iconArmor,itemid,itemid,toolTip,itemid,name,moduleName,itemid,iconArmor,itemid,itemid,toolTip)
        scripts.modelScript = scripts.modelScript .. string.format(DakiData.DakiScript.models,itemid,texture,itemid,texture,itemid,texture,itemid,texture,itemid,texture)

    end
end

local function CompileMangaScripts(type,name,texture,icon,mangaid)
    if CheckManga(type) then
        local toolTip
        if toolTips.manga[name] then
            toolTip = "Tooltip_"..name
        else toolTip = ""
        end
        if icon then icon = "manga" .. mangaid
        else icon = "OppaiZ" end
        scripts.mangaScript = scripts.mangaScript .. string.format(DakiData.MangaScript.items,mangaid,name,icon,mangaid,mangaid,toolTip)
        scripts.mangaModels = scripts.mangaModels .. string.format(DakiData.MangaScript.models,mangaid,texture,mangaid,texture)
    end
end

local function WriteToModInfo(filePath,modName,modInfotxt)
    local moduleName = string.gsub(modName, "%s+", "")

                local writer = getFileWriter(filePath .. "workshop.txt", true, false)           --writing to workshop.txt here
                writer:write(string.format(DakiData.workshopTxt,modInfotxt,getCurrentUserProfileName()))
                writer:close()

                local modInfo = string.format(DakiData.modInfo,modInfotxt,moduleName,getCurrentUserProfileName())  --writing to mod.info here
                writer = getFileWriter(filePath .. "Contents/mods/" .. modName .. "/42/mod.info",true,false)
                writer:write(modInfo)
                writer:close()

            --[[
                writer = getFileWriter(filePath .. "Contents/mods/" .. modName.. "/42/media/textures/info.txt",true,false) --file written here to make texture folder and give info
                writer:write(DakiData.texInfo)
                writer:close()
            --]]

                local writer = getFileWriter(filePath .. "Contents/mods/" .. modName .. "/42/media/textures/" .. moduleName .. "/info.txt",true,false)
                writer:write("put all textures in this folder")
                writer:close()
            
                writer = getFileWriter(filePath .. "Contents/mods/" .. modName.. "/common/info.txt",true,false) --file written here to make common folder and give info
                writer:write("here to make this directory only")
                writer:close()
end

local sStarts = luautils.stringStarts
while run do --should run on second load and start looping through .ini file

    local line = reader:readLine()
    
    if line == nil then reader:close() break end   --if a line is empty it breaks and assumes its finished
        line = string.trim(line)
    if not sStarts(line, "##") then                       --skip comment lines 


        local upperLine = string.upper(line)
        if line == '' then
        elseif sStarts(upperLine, "MODNAME") then
                                                 -- find modname first
                modName = string.match(line, "=(.*)")
                if sStarts(modName, "#Test") then break end 
                if not modName or modName == "" then                                            --breaks when no mod name writes an error.txt
                        modName = "*Dakimakura Addon"
                end
                
                if sStarts(modName, "*") then                                     --customized mod name
                    modName = modName:sub(2)
                    filePath = "DakiScript/" .. modName .. "/"
                    modInfotxt = modName
                    modPath = modName
                else
                filePath = "DakiScript/Dakimakura_".. modName .. "_Addon/"          --pathing references filled here
                modPath = "Dakimakura_".. modName .. "_Addon"
                modInfotxt = "Dakimakura ".. modName .. " Addon"
                end
        elseif sStarts(upperLine, "TYPE=") then
            local type = string.match(line, "=(.*)")
            if CheckDaki(type) then
            dakiType = type
            makeWhat = "daki"
            elseif CheckManga(type) then
            mangaType = type
            makeWhat = "manga"
            end
        elseif sStarts(upperLine, "ICON=")then --check if icons are provided
            local bool = string.match(line, "=(.*)")
            bool = string.upper(bool)
            bool = sStarts(bool,"TRUE")
            if bool then
                if sStarts(makeWhat,"daki") then doDakiIcons = true end
                if sStarts(makeWhat,"manga") then doMangaIcons = true end
            else
                if sStarts(makeWhat,"daki") then doDakiIcons = false end
                if sStarts(makeWhat,"manga") then doMangaIcons = false end
            end
        else         --will pass here after modname is found

                if  dakiType and sStarts(makeWhat,"daki") then
                    local lastWord
                    for word in string.gmatch(line, '([^,]+)') do
                        local upWord = string.upper(word)
                        if sStarts(upWord,"TOOLTIP") then
                            toolTips.setToolTips = true
                            local tooltip = string.match(line, "=(.*)")
                            toolTips.daki[lastWord] = tooltip
                        elseif word and word ~= "" then table.insert(massDaki,word)
                        lastWord = word
                        end
                        
                    end
                elseif mangaType and sStarts(makeWhat,"manga") then
                        local lastWord
                    for word in string.gmatch(line, '([^,]+)') do
                        local upWord = string.upper(word)
                        if sStarts(upWord,"TOOLTIP") then
                            toolTips.setToolTips = true
                            local tooltip = string.match(line, "=(.*)")
                            toolTips.manga[lastWord] = tooltip
                        elseif word and word ~= "" then table.insert(massManga,word)
                        lastWord = word
                        end
                    end
                end

                if not (dakiType or mangaType) then       --if any variables aren't filled it breaks and prints to error.txt
                    local writer = getFileWriter("DakiScript/DakiError.txt", true, true)
                    writer:write(" --type missing from parameters-- ")
                    writer:close()
                    break
                end
                
        end
    end
end

if (dakiType and modName) or (mangaType and modName) then
    local moduleName = string.gsub(modName, "%s+", "")
    if (dakiType and modName) then
        for i,name in pairs(massDaki) do
            local dakiTex = moduleName .. "/daki"..i
            CompileDakiScripts(dakiType,name,dakiTex,doDakiIcons,i)
        end
    end
    if (mangaType and modName) then
        for i,name in pairs(massManga) do
            local dakiTex = moduleName .. "/manga"..i
            CompileMangaScripts(mangaType,name,dakiTex,doMangaIcons,i)
        end
        
    end
  
    local dakiList
    local outfitDefs
    
    WriteToModInfo(filePath,modName,modInfotxt)
    filePath = filePath .. "Contents/mods/" .. modName .. "/42/media/" -- moving filepath deeper
    local dakiListWriter = getFileWriter(filePath .. "lua/shared/DakiList.lua", true, false) --writes to dakilist.lua
    dakiListWriter:write([[local DakimakuraWeapons = require("DakimakuraList")]])
    local outfitDefWriter = getFileWriter(filePath .. "lua/shared/DakiOutfitDefinitions.lua", true, false) --writes to outfitdefinitions.lua
    outfitDefWriter:write(DakiData.OutfitDefs)

    local writer = getFileWriter(filePath .. "fileGuidTable.xml",true,false) -- start fileGuid.xml
    writer:write("<fileGuidTable>")
    writer:close()
    -- everything that's not scripts written to file here
    if dakiType then
        for i,name in pairs(massDaki)do -- iterate through all of the items listed
        
            dakiList =  "\r\n" .. [[DakimakuraWeapons:add("]]..moduleName..[[.Dakimakura]]..i..[[")]]
            dakiListWriter:write(dakiList)
            
            --writes to outfitdefinitions.lua
            outfitDefs =  "\r\n" .. [[table.insert(AttachedWeaponDefinitions.DakimakuraInBack.weapons, "]] .. moduleName ..".".."Dakimakura"..i.. [[")]]
            outfitDefWriter:write(outfitDefs)
            
            --write to armor clothing xmls
            local backUUid = getRandomUUID() --getting guid for clothing
            local frontUUid = getRandomUUID()
            local frontPath = filePath .. "clothing/clothingItems/"..moduleName..".Dakimakura"..i.."_FrontArmor.xml" --making proper file paths
            local backPath = filePath .. "clothing/clothingItems/"..moduleName..".Dakimakura"..i.."_BackArmor.xml"
            writer = getFileWriter(backPath, true, false)
            writer:write(string.format(DakiData.ArmorBackXml,backUUid,moduleName .. "\\daki"..i)) --back armor xml write
            writer:close()
            writer = getFileWriter(frontPath, true, false)
            writer:write(string.format(DakiData.ArmorFrontXml,frontUUid,moduleName .. "\\daki"..i)) --front armor xml write
            writer:close()
            
            --write to fileGuid xml
            writer = getFileWriter(filePath .. "fileGuidTable.xml",true,true)
            writer:write("\r\n" .. string.format(DakiData.FileGuideTable,string.gsub(backPath,"DakiScript/"..modPath.."/Contents/mods/"..modName.."/42/",""),backUUid))
            writer:write("\r\n" .. string.format(DakiData.FileGuideTable,string.gsub(frontPath,"DakiScript/"..modPath.."/Contents/mods/"..modName.."/42/",""),frontUUid))
            writer:close()
        end
        writer = getFileWriter(filePath .. "fileGuidTable.xml",true,true)               --close fileguid xml
        writer:write("\r\n" .."</fileGuidTable>")
        writer:close()
        dakiListWriter:close()  -- close the rest of xml writers
        outfitDefWriter:close() 
    end


    --manga lua filewriting here
    if mangaType then
        local mangaList = ""
        for id,name in pairs(massManga)do
            mangaList = mangaList .. "\r\n" .. [[OpaiZList:add("]]..moduleName..[[.Manga]]..id..[[")]]
        end
        writer = getFileWriter(filePath .. "lua/shared/MangaList.lua", true, false)
        writer:write([[local OpaiZList = require("OpaiZList")]].."\r\n")    
        writer:write(mangaList)
        writer:close()
    end

    --write tooltip translations
    if toolTips.setToolTips then
        local mangaToolTip = ""
        local dakiToolTip = ""
        for name , tooltip in pairs(toolTips.daki)do
            dakiToolTip = dakiToolTip.."\r\n".."Tooltip_"..name..[[ = "]]..tooltip..[[",]]
        end
        for name , tooltip in pairs(toolTips.manga)do
            mangaToolTip = mangaToolTip.."\r\n".."Tooltip_"..name..[[ = "]]..tooltip..[[",]]
        end
            local compiledToolTips = dakiToolTip .. "\r\n" .. mangaToolTip

        if compiledToolTips and compiledToolTips ~= "" then
            local tooltipWriter = getFileWriter(filePath .. "lua/shared/Translate/EN/Tooltip_EN.txt", true, false)
            tooltipWriter:write(string.format(DakiData.ToolTip,compiledToolTips))
            tooltipWriter:close()
        end
    end

    
    -- where all scripts are written to file
    if (scripts.itemScript and scripts.itemScript ~="") and (scripts.modelScript and scripts.modelScript ~="") and (scripts.armorScript and scripts.armorScript ~="")then
        writer = getFileWriter(filePath .. "scripts/" .. moduleName .. "DakiItemScript.txt", true, false)
        writer:write("module " .. moduleName .. " { " .. scripts.itemScript .. "}")
        writer:close()

        writer = getFileWriter(filePath .. "scripts/" .. moduleName .. "DakiModelScript.txt", true, false)
        writer:write("module " .. moduleName .. " { " .. scripts.modelScript .. "}")
        writer:close()

        writer = getFileWriter(filePath .. "scripts/" .. moduleName .. "DakiArmorItemScript.txt", true, false)
        writer:write("module " .. moduleName .. " { " .. scripts.armorScript .. "}")
        writer:close()

    end
    if (scripts.mangaScript and scripts.mangaScript ~= "") and (scripts.mangaModels and scripts.mangaModels ~= "") then
        writer = getFileWriter(filePath .. "scripts/" .. moduleName .. "MangaItemScript.txt", true, false)
        writer:write("module " .. moduleName .. " { " .. scripts.mangaScript .. "}")
        writer:close()

        writer = getFileWriter(filePath .. "scripts/" .. moduleName .. "MangaModelScript.txt", true, false)
        writer:write("module " .. moduleName .. " { " .. scripts.mangaModels .. "}")
        writer:close()
    end
end

