local https = require('ssl.https')
local ltn12 = require('ltn12')
local multipart = require('multipart-post')
local json = require('dkjson')
local request = function(endpoint, parameters)
    parameters = parameters or {}
    for k, v in pairs(parameters) do
        parameters[k] = tostring(v)
    end
    if next(parameters) == nil then
        parameters = {
            ''
        }
    end
    local response = {}
    local body, boundary = multipart.encode(parameters)
    local success, code = https.request(
        {
            ['url'] = endpoint,
            ['method'] = 'POST',
            ['headers'] = {
                ['Content-Type'] = 'multipart/form-data; boundary=' .. boundary,
                ['Content-Length'] = #body
            },
            ['source'] = ltn12.source.string(body),
            ['sink'] = ltn12.sink.table(response)
        }
    )
    if not success then
        return false, code
    end
    local jdat = table.concat(response)
    if not json.decode(jdat) then
        return jdat, code
    end
    jdat = json.decode(jdat)
    if jdat.ok == true then
        return jdat, code
    end
    return false, jdat
end
io.write('\nWhat is your phone number? [Enter it in the format +447712345678, with the country code (i.e. +44) and the number, with no spaces]\n')
local phone = io.read()
local success = request(
    'https://api.pwrtelegram.xyz/phoneLogin',
    {
        ['phone'] = tostring(phone)
    }
)
if not success then
    io.write('\nThat\'s not a valid phone number! Please make sure you\'ve specified it with the country code, and try again.\n')
    return
end
local temp_access_token = success.result
io.write('\nPlease state the code you just received from Telegram:\n')
local code = io.read()

if tonumber(code) == nil or tostring(code):len() ~= 5 then
    io.write('\nInvalid code!\n')
    return
end
success = request(
    string.format(
        'https://api.pwrtelegram.xyz/user%s/completePhoneLogin',
        temp_access_token
    ),
    {
        ['code'] = tonumber(code)
    }
)

local permanent_access_token = ''
if not success then
    io.write('\nHm. An error seems to have occured. Do you have a 2FA password on your Telegram account? (y/n)\n')
    local password = io.read()
    if password:lower():match('^n') then
        io.write('\nIn that case, I\'m not sure what went wrong. Please try again later!\n')
        return
    end
    io.write('What is your 2FA password?')
    password = io.read()
    success = request(
        string.format(
            'https://api.pwrtelegram.xyz/user%s/complete2FALogin',
            temp_access_token
        ),
        {
            ['password'] = tostring(password)
        }
    )
    if not success then
        io.write('\nInvalid password - try again!\n')
        io.write('What is your 2FA password?')
        password = io.read()
        success = request(
            string.format(
                'https://api.pwrtelegram.xyz/user%s/complete2FALogin',
                temp_access_token
            ),
            {
                ['password'] = tostring(password)
            }
        )
        if not success then
            io.write('\nInvalid password - aborting!\n')
            return
        end
    end
    permanent_access_token = success.result
else
    permanent_access_token = success.result
end
io.write('\nSuccessfully connected to PWRTelegram - saving access token for future use (you can revoke this access in your Telegram security settings)!\n')
io.write('\nWould you like to set this backend on a bot you own? y/n\n')
local token = io.read()
if token:lower():match('^n') then
    io.write('\nOk then, you\'re finished.\n')
    return
end
io.write('\nOk, please enter the bot token you would like to set the backend for:\n')
token = io.read()
success = request(
    string.format(
        'https://api.pwrtelegram.xyz/bot%s/setBackend',
        token
    ),
    {
        ['backend_token'] = permanent_access_token
    }
)
if not success then
    io.write('\nI couldn\'t set the backend for that bot, aborting!\n')
    return
end
io.write('\nSuccessfully set the backend for @' .. request(
    string.format(
        'https://api.telegram.org/bot%s/getMe',
        token
    )
).result.username:lower() .. '!\nYour permanent access token is:\n' .. permanent_access_token .. '\n\nPlease write it down/store it somewhere safe!')
return