/*******************************************************************************
  XDG desktop portal implementation for TDE
  Copyright © 2024 Mavridis Philippe <mavridisf@gmail.com>

  This program or library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public License as
  published by the Free Software Foundation; either version 2.1 of the License,
  or (at your option) any later version.

  This library 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 Lesser General Public License for more
  details.

  You should have received a copy of the GNU Lesser General Public License
  along with this library; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

  Improvements and feedback are welcome!
*******************************************************************************/

#ifndef __DIALOG_RESULT_SENDER_H
#define __DIALOG_RESULT_SENDER_H

// TQt
#include <tqthread.h>
#include <tqdialog.h>

// Portal
#include "util.h"

struct DialogResult
{
    TQ_UINT32 response;
    TQT_DBusVariantMap results;
};

template <class T>
using ResultPrepareCallback = DialogResult(T::*)(TQDialog*);

template <class T>
using ResultSendCallback = void(T::*)(int, TQ_UINT32, const TQT_DBusVariantMap&);

template <class T>
class DialogResultSender : public TQThread
{
    public:
        DialogResultSender(T* portal, int asyncCallId, TQDialog *dlg, ResultPrepareCallback<T> prepareCb, ResultSendCallback<T> sendCb)
            : TQThread(),
              m_portal(portal),
              m_asyncCallId(asyncCallId),
              m_dlg(dlg),
              m_prepareCb(prepareCb),
              m_sendCb(sendCb)
        {}

        ~DialogResultSender()
        {
            wait();
        }

        void run()
        {
            if (!m_dlg) return;

            while (m_dlg->isVisible())
            {
                usleep(1000);
            }

            DialogResult res = (m_portal->*m_prepareCb)(m_dlg);
            (m_portal->*m_sendCb)(m_asyncCallId, res.response, res.results);

            m_dlg->deleteLater();
        }

    private:
        T *m_portal;
        int m_asyncCallId;
        TQDialog *m_dlg;
        ResultPrepareCallback<T> m_prepareCb;
        ResultSendCallback<T> m_sendCb;
};

#endif // __DIALOG_RESULT_SENDER_H