--[[
    Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com>
    This code is licensed under the MIT. See LICENSE for details.
]]

local instagram = {}
local mattata = require('mattata')
local https = require('ssl.https')
local url = require('socket.url')
local ltn12 = require('ltn12')
local json = require('dkjson')

function instagram:init()
    instagram.commands = mattata.commands(self.info.username)
    :command('instagram')
    :command('ig').table
    instagram.help = '/instagram <Instagram username> - Sends the profile picture of the given Instagram user. Alias: /ig.'
end

function instagram.get_profile_pic(username)
    if not username then
        return false, "No username provided!"
    end
    local jstr, res = https.request('https://www.instadp.com/api/s2/' .. url.escape(username))
    if res ~= 200 then
        return false, "Connection error!"
    end
    jstr = jstr:gsub('\\', ''):gsub('%s+', '') -- trim whitespace
    local jdat = json.decode(jstr:match('^"(.-)"$'))
    if not jdat.data or not jdat.data[1] then
        return false, "No results found!"
    end
    return jdat.data[1].picture
end

function instagram:on_inline_query(inline_query, configuration, language)
    local input = mattata.input(inline_query.query)
    if not input then
        return
    end
    local pic, err = instagram.get_profile_pic(input)
    if not pic then
        return false, err
    end
    return mattata.send_inline_photo(inline_query.id, pic)
end

function instagram:on_message(message, configuration, language)
    local input = mattata.input(message.text)
    if not input then
        return mattata.send_reply(message, instagram.help)
    end
    local pic, err = instagram.get_profile_pic(input)
    if not pic then
        return mattata.send_reply(message, err)
    end
    local keyboard = mattata.inline_keyboard():row(
        mattata.row():url_button(
            string.format(
                language['instagram']['1'],
                input
            ),
            'https://www.instagram.com/' .. input
        )
    )
    return mattata.send_photo(message.chat.id, pic, nil, false, nil, keyboard)
end

return instagram