--@name gTTs
--@shared

URL = "https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob"
TTS = class("TTS")

if SERVER then

    function TTS:initialize(parent, lang, pitch)
        self.parent = parent or nil
        self.lang = lang or "en"
        self.pitch = pitch or 1
        self.LFO = false
    end
    
    function TTS:say(text)
        if not self.parent or not text then return end
        
        net.start("starfall_tts")
            net.writeString(text)
            net.writeString(self.lang)
            net.writeFloat(math.clamp(self.pitch, 0, 100))
            net.writeBool(self.LFO)
            net.writeEntity(self.parent)
        net.send()
    end
    
    function TTS:setLFO(a)
        self.LFO = a
    end
    
end

if CLIENT then
    function parentSound(soun, ent , LFO)
        local name = "Parent"..tostring(ent:entIndex())..tostring(math.rand(0,100))
        local a = 0
        hook.add("Think", name, function()
            if not soun or soun:isStopped() then
                soun:destroy()
                hook.remove("Think", name)
                return
            end
            if LFO then
                a = a + 0.7
                soun:setPitch(math.sin(a)/10+1)
            end
            soun:setPos(ent:getPos())
        end)
    end
    
    net.receive("starfall_tts", function()
        local text = net.readString()
        local lang = net.readString()
        local pitch = net.readFloat()
        local LFO = net.readBool()
        net.readEntity(function(parent)
            local parent = parent
            local encodedText = http.urlEncode(text)
            if not encodedText or encodedText == "" then return end
            
            local fullURL = string.format("%s&tl=%s&q=%s", URL, lang, encodedText)
            
            bass.loadURL(fullURL, "3d", function(soun)
                soun:setPitch(pitch)
                soun:setVolume(100)
                soun:setFade(50, 1600, true)
                soun:play()
                parentSound(soun , parent, LFO)
            end)
        end)
    end)
end
