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

local itunes = {}
local mattata = require('mattata')
local https = require('ssl.https')
local url = require('socket.url')
local json = require('dkjson')
local redis = require('libs.redis')

function itunes:init()
    itunes.commands = mattata.commands(self.info.username):command('itunes').table
    itunes.help = '/itunes <query> - Searches iTunes for the given search query and returns the most relevant result.'
end

function itunes.get_output(jdat, language)
    local output = {}
    if jdat.results[1].trackViewUrl
    and jdat.results[1].trackName
    then
        table.insert(
            output,
            '<b>' .. language['itunes']['1'] .. '</b> <a href=\'' .. jdat.results[1].trackViewUrl .. '\'>' .. mattata.escape_html(jdat.results[1].trackName) .. '</a>'
        )
    end
    if jdat.results[1].artistViewUrl
    and jdat.results[1].artistName
    then
        table.insert(
            output,
            '<b>' .. language['itunes']['2'] .. '</b> <a href="' .. jdat.results[1].artistViewUrl .. '">' .. mattata.escape_html(jdat.results[1].artistName) .. '</a>'
        )
    end
    if jdat.results[1].collectionViewUrl
    and jdat.results[1].collectionName
    then
        table.insert(
            output,
            '<b>' .. language['itunes']['3'] .. '</b> <a href="' .. jdat.results[1].collectionViewUrl .. '">' .. mattata.escape_html(jdat.results[1].collectionName) .. '</a>'
        )
    end
    if jdat.results[1].trackNumber
    and jdat.results[1].trackCount
    then
        table.insert(
            output,
            '<b>' .. language['itunes']['4'] .. '</b> ' .. jdat.results[1].trackNumber .. '/' .. jdat.results[1].trackCount
        )
    end
    if jdat.results[1].discNumber
    and jdat.results[1].discCount
    then
        table.insert(
            output,
            '<b>' .. language['itunes']['5'] .. '</b> ' .. jdat.results[1].discNumber .. '/' .. jdat.results[1].discCount
        )
    end
    return table.concat(
        output,
        '\n'
    )
end

function itunes:on_inline_query(inline_query)
    local input = mattata.input(inline_query.query)
    if not input
    then
        return
    end
    local jstr, res = https.request('https://itunes.apple.com/search?term=' .. url.escape(input))
    if res ~= 200
    then
        return
    end
    local jdat = json.decode(jstr)
    if not jdat.results[1]
    then
        return
    end
    local count = 0
    local results = {}
    local temp = {}
    for k, v in pairs(jdat.results)
    do
        if v.artworkUrl100
        and not temp[v.artworkUrl100]
        then
            count = count + 1
            table.insert(
                results,
                mattata.inline_result()
                :type('photo')
                :id(count)
                :photo_url(
                    v.artworkUrl100
                    :gsub('%/100x100bb%.jpg', '/10000x10000bb.jpg')
                )
                :thumb_url(v.artworkUrl100)
            )
            temp[v.artworkUrl100] = true
        end
    end
    return mattata.answer_inline_query(
        inline_query.id,
        results
    )
end

function itunes:on_callback_query(callback_query, message, configuration, language)
    if not message.reply
    then
        return mattata.answer_callback_query(
            callback_query.id,
            language['itunes']['6'],
            true
        )
    end
    local input = mattata.input(message.reply.text)
    if callback_query.data == 'artwork'
    then
        local jstr, res = https.request('https://itunes.apple.com/search?term=' .. url.escape(input))
        if res ~= 200
        then
            return false
        end
        local jdat = json.decode(jstr)
        if not jdat.results[1]
        then
            return false
        end
        if jdat.results[1].artworkUrl100
        then
            local artwork = jdat.results[1].artworkUrl100:gsub('%/100x100bb%.jpg', '/10000x10000bb.jpg')
            -- Get the highest quality artwork available.
            mattata.send_photo(
                message.chat.id,
                artwork
            )
            return mattata.edit_message_text(
                message.chat.id,
                message.message_id,
                language['itunes']['7']
            )
        end
    end
end

function itunes:on_message(message, configuration, language)
    local input = mattata.input(message.text)
    if not input
    then
        local success = mattata.send_force_reply(
            message,
            language['itunes']['8']
        )
        if success
        then
            redis:set(
                string.format(
                    'action:%s:%s',
                    message.chat.id,
                    success.result.message_id
                ),
                '/itunes'
            )
        end
        return
    end
    mattata.send_chat_action(message.chat.id)
    local jstr, res = https.request('https://itunes.apple.com/search?term=' .. url.escape(input))
    if res ~= 200
    then
        return mattata.send_reply(
            message,
            language['errors']['connection']
        )
    end
    local jdat = json.decode(jstr)
    if not jdat.results[1]
    then
        return mattata.send_reply(
            message,
            language['errors']['results']
        )
    end
    return mattata.send_message(
        message.chat.id,
        itunes.get_output(
            jdat,
            language
        ),
        'html',
        true,
        false,
        message.message_id,
        mattata.inline_keyboard():row(
            mattata.row():callback_data_button(
                language['itunes']['9'],
                'itunes:artwork'
            )
        )
    )
end

return itunes