/*
 * Kylin-video
 *
 * Copyright (C) 2021, Tianjin KYLIN Information Technology Co., Ltd.
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Authors: Liu Cong <liucong1@kylinos.cn>
 *
 */

#include "dbusadapter.h"
#include <QDBusConnection>
#include "global/globalsignal.h"

DbusAdapter::DbusAdapter(QObject *parent) : QObject(parent)
{
    m_playState = Mpv::Idle;
    m_currentFile = "";

    connect(g_core_signal, &GlobalCoreSignal::sigStateChange, [&](Mpv::PlayState state){
        m_playState = state;
        if(m_playState < 0)
            m_currentFile = "";
    });
    connect(g_core_signal, &GlobalCoreSignal::sigFileInfoChange, [&](Mpv::FileInfo fi){
        m_currentFile = fi.file_path;
    });

    QDBusConnection::sessionBus().unregisterService("org.mpris.MediaPlayer2.KylinVideo");
    QDBusConnection::sessionBus().registerService("org.mpris.MediaPlayer2.KylinVideo");
    QDBusConnection::sessionBus().registerObject("/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player", this, QDBusConnection::ExportNonScriptableSlots);
}

void DbusAdapter::Stop() const
{
    g_user_signal->stop();
    // 手动停止之后需要显示默认界面
    g_user_signal->showStopFrame();
}

void DbusAdapter::Next() const
{
//    g_user_signal->stop();
//    g_user_signal->play();
    g_user_signal->playNext(true);
}

void DbusAdapter::KvPlayPause() const
{
    if(m_playState == Mpv::Paused)
        g_user_signal->play();
    else if(m_playState == Mpv::Playing)
        g_user_signal->pause();
}

void DbusAdapter::Previous() const
{
    g_user_signal->playPrev(true);
}

void DbusAdapter::AddFile(QString file) const
{
    g_user_signal->addFiles(QStringList() << file);
}

void DbusAdapter::VolumeUp() const
{
    g_user_signal->setVolumeUp();
}

void DbusAdapter::VolumeDown() const
{
    g_user_signal->setVolumeDown();
}

void DbusAdapter::FullScreen() const
{
    g_user_signal->fullScreen();
}

void DbusAdapter::LoopMode() const
{
    g_user_signal->changePlayOrder();
}

void DbusAdapter::Exit() const
{
    g_user_signal->exitApp();
}

/**
 * 返回播放状态
 * @return:
 *  -1  :停止
 *  0   :暂停
 *  1   :播放
 */
int DbusAdapter::PlayState()
{
    if(m_playState == Mpv::Playing)
        return 1;
    else if(m_playState == Mpv::Paused)
        return 0;
    else
        return -1;
}

QString DbusAdapter::CurrentFile()
{
    return m_currentFile;
}
