#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "Playsdk/play.h"
#include <QFile>
#include <Android/native_window_jni.h>
#include <QtCore/private/qandroidextras_p.h>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_nPort(0)
{
    ui->setupUi(this);
     PLAY_SetPrintLogLevel(LOG_LevelInfo);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    auto resultCheck = QtAndroidPrivate::checkPermission("android.permission.WRITE_EXTERNAL_STORAGE");
    auto resultRequest= QtAndroidPrivate::requestPermission("android.permission.WRITE_EXTERNAL_STORAGE");

    //问题：Qt内部已经使用窗口Surface创建opengl EGL surface，libplay.so再使用该窗口Surface创建opengl EGL surface失败（OpenGL中eglCreateWindowSurface接口对于一个窗口句柄只能调用一次）。
    //报错：E libEGL  : eglCreateWindowSurface: native_window_api_connect (win=0xe8bce2c8) failed (0xffffffea) (already connected to another API?)
    //playVideo接口实现的是播放本地视频文件test.mp4,libplay.so库用来实现播放本地视频文件
    QString strFile = "/storage/emulated/0/test.mp4";
    bool bret = playVideo(strFile);
    qDebug(bret ? "play Success" : "play fail");
}

bool MainWindow::playVideo(QString strFile)
{
    QFile file(strFile);
    if (!file.exists())
    {
        qDebug("CPlaySdkPlayer::openStream file[%s] no exists",
               strFile.toStdString().c_str());
        return false;
    }

    if (!PLAY_GetFreePort(&m_nPort))
    {
        qDebug("PLAY_GetFreePort failed file[%s], erro[%d]",
               strFile.toStdString().c_str(),
               PLAY_GetLastErrorEx());
        return false;
    }

    if (!PLAY_OpenFile(m_nPort, (LPSTR)(strFile.toLocal8Bit().toStdString().c_str())))
    {
        qDebug("PLAY_OpenFile failed file[%s], erro[%d]",
               strFile.toStdString().c_str(),
               PLAY_GetLastErrorEx());
        PLAY_ReleasePort(m_nPort);
        m_nPort = 0;
        return false;
    }

    //play
    jobject jobj = reinterpret_cast<jobject>(winId());
    if(!jobj)
    {
        qDebug("jobj(jobject) is null");
        return false;
    }
    else
    {
        qDebug("w.winId()=%u", winId());
        QJniObject qjni = QJniObject(jobj);
        qjni.callObjectMethod("getLayout","()Lorg/qtproject/qt/android/QtLayout;");
        QJniObject qjniQtLayout = qjni.callObjectMethod("getLayout","()Lorg/qtproject/qt/android/QtLayout;");
        qDebug("QtLayoutJobject()=%p", qjniQtLayout.object());
        QJniObject qjniQtSurface = qjniQtLayout.callObjectMethod("getChildAt","(I)Landroid/view/View;",0);
        qDebug("QtSurfaceJobject()=%p", qjniQtSurface.object());
        QJniObject qjniSurfaceHolder = qjniQtSurface.callObjectMethod("getHolder","()Landroid/view/SurfaceHolder;");
        qDebug("SurfaceHolderJobject()=%p", qjniSurfaceHolder.object());
        QJniObject qjniSurface = qjniSurfaceHolder.callObjectMethod("getSurface","()Landroid/view/Surface;");
        qDebug("SurfaceJobject()=%p",qjniSurface.object());

        JNIEnv* jni = QJniEnvironment::getJniEnv();
        ANativeWindow* nativeWindow = ANativeWindow_fromSurface(jni,qjniSurface.object());

        int width = ANativeWindow_getWidth(nativeWindow);
        int height = ANativeWindow_getHeight(nativeWindow);
        qDebug("nativeWindow=%p,width=%d,height=%d",nativeWindow,width,height);

        if (!PLAY_Play(m_nPort, (HWND)(nativeWindow)))
        {
            qDebug("PLAY_Play failed m_nPort[%d] erro[%d]",
                   m_nPort,
                   PLAY_GetLastErrorEx());
            if (PLAY_ReleasePort(m_nPort))
            {
                m_nPort = 0;
            }

            return false;
        }

        return true;
    }
}
