/*Copyright (C) 2010-2023 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Hikou no mizu is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "PlaylistNotifier.hpp"

#include "Tools/ScaledPixel.hpp"

namespace
{
    constexpr std::chrono::seconds NOTIFY_TIME(2);
    constexpr float NOTIFIER_WIDTH = 300.f;
    constexpr float NOTIFIER_HEIGHT = 65.f;
}

PlaylistNotifier::PlaylistNotifier(float viewWidth) : Drawable(),
m_viewWidth(viewWidth), m_updated(false),
m_background(Polygon::rectangle(ScaledPixel{m_viewWidth}(NOTIFIER_WIDTH),
                                ScaledPixel{m_viewWidth}(NOTIFIER_HEIGHT),
                                Color(66, 112, 174), Color(84, 126, 181))),
m_notifying(false)
{
    const ScaledPixel sp(m_viewWidth);

    m_background.setBorderSize(sp(15.f));

    m_titleText.setColor(Color(255, 255, 255));
    m_authorText.setColor(Color(255, 255, 255, 200));

    m_titleText.setPosition(sp(20.f), sp(15.f));
    m_authorText.setPosition(sp(20.f), sp(35.f));
}

void PlaylistNotifier::draw()
{
    //Update matrix
    Drawable::pushMatrix();
    Drawable::updateMatrix();

    bool notifying;
    {
        std::lock_guard<std::mutex> lock(m_mutex);
        notifying = m_notifying;
    }

    if (notifying)
    {
        m_background.draw();

        m_authorText.draw();
        m_titleText.draw();
    }

    Drawable::popMatrix();
}

void PlaylistNotifier::update()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    if (m_updated)
    {
        m_authorText.setText(m_author);
        m_titleText.setText(m_title);
        m_updated = false;
    }

    if (m_notifying && m_notifyTimer.getTicks() >= NOTIFY_TIME)
        m_notifying = false;
}

void PlaylistNotifier::notify(const std::string &author,
                              const std::string &title)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    m_author = author;
    m_title = title;
    m_updated = true;
    m_notifying = true;
    m_notifyTimer.reset();
}

void PlaylistNotifier::setFonts(Font &titleFont, Font &authorFont)
{
    m_titleText.setFont(titleFont);
    m_authorText.setFont(authorFont);
}

float PlaylistNotifier::getWidth() const
{
    return ScaledPixel{m_viewWidth}(NOTIFIER_WIDTH);
}

float PlaylistNotifier::getHeight() const
{
    return ScaledPixel{m_viewWidth}(NOTIFIER_HEIGHT);
}
