#include "use_screen.h"



Use_Screen::Use_Screen(QWidget *parent) : QWidget(parent)
{
    ui.setupUi(this);
    connect(ui.btn_screen_subscribe, SIGNAL(toggled(bool)), this, SLOT(on_subscribeRemoteScreen(bool)));
    bool ret = connect(ui.btn_screen_pub, SIGNAL(toggled(bool)), this, SLOT(on_publishScreen(bool)));
#ifdef USED_VIDEOVIEW2
    remoteScreen_ = new CVideoView2(ui.lst_screen_remoteview,2);
#endif

    remoteScreen_->updateViewSize(ui.lst_screen_remoteview->width(), ui.lst_screen_remoteview->height());
    remoteScreen_->setScalingType(IVideoRenderView::Scale_Aspect_Fit);
    ui.lineEdit->setText("1920");
    ui.lineEdit_4->setText("1080");
    ui.lineEdit_5->setText("15");

    ui.lineEdit_2->setText("2000");
    ui.lineEdit_3->setText("4000");

    ui.lineEdit_6->setText("0");
    ui.lineEdit_7->setText("0");
    ui.lineEdit_8->setText("0");
    ui.lineEdit_9->setText("0");


}
void Use_Screen::onAttach(rtc::IRoom* room){
    if (nullptr == room) {
        module_ = nullptr;
    }
    else {
        module_ = IMScreen::getScreen(room);
        module_->setListener(this);

        ScreensType items_;
        module_->getScreenWindows(items_);
        for(size_t i=0;i<items_.size();++i){
            QListWidgetItem* item = new QListWidgetItem;
            item->setData(Qt::DisplayRole, items_[i].name.c_str());
            item->setData(Qt::UserRole, items_[i].id.c_str());
            ui.lst_screen_lst->addItem(item);
        }

        qDebug()<<"remote render = "<<remoteScreen_->getRender();


    }
}
void Use_Screen::onDetach(){
    if (module_) {
        module_->setListener(NULL);
        module_ = NULL;
    }
    ui.lst_screen_lst_remote->clear();
    ui.lst_screen_lst->clear();
    ButtonChecked(ui.btn_screen_pub, false, Utf8Str("pubscrn"));
    ButtonChecked(ui.btn_screen_subscribe, false, Utf8Str("订阅"));
}
void Use_Screen::onScreenStatusNotify(ScreenStatus status, const DeviceId& fromId){
    qDebug()<<"onScreenStatusNotify "<<status<<","<<fromId.c_str();
}
void Use_Screen::onScreenDataNotify(int level, const String& description, const DeviceId& fromId) {
    qDebug()<<"onScreenDataNotify";
}
void Use_Screen::onPublishScreenNotify(const ScreenWindow& screen){
    qDebug()<<"onPublishScreenNotify";
    bool isself = module_->isSelfUser(module_->getOwnerId(screen.id));
    if(!isself){
        QListWidgetItem* item = new QListWidgetItem;
        item->setData(Qt::DisplayRole, screen.name.c_str());
        item->setData(Qt::UserRole, screen.id.c_str());
        ui.lst_screen_lst_remote->addItem(item);
    }
}
void Use_Screen::onUnpublishScreenNotify(const ScreenWindow& screen){
    qDebug()<<"onUnpublishScreenNotify";

    int idx = 0;
    for (; idx < ui.lst_screen_lst_remote->count(); ++idx) {
        QString curId = ui.lst_screen_lst_remote->item(idx)->data(Qt::UserRole).toString();
        if (curId == screen.id.c_str()) {
            ui.lst_screen_lst_remote->takeItem(idx);
        }
    }
}
void Use_Screen::onSubscribeScreenResult(Result result, const DeviceId& fromId) {
    qDebug()<<"onSubscribeScreenResult "<<result<<","<<fromId.c_str();
    if (!isAttach()) {
        return ;
    }
    module_->attachRender(fromId,remoteScreen_->getRender());
}
void Use_Screen::onUnsubscribeScreenResult(Result result, const DeviceId& fromId){
    qDebug()<<"onUnsubscribeScreenResult "<<result<<","<<fromId.c_str();
    if (!isAttach()) {
        return ;
    }
    module_->detachRender(remoteScreen_->getRender());
}
void Use_Screen::onPublishScreenResult(Result result, const DeviceId& fromId) {
    if (module_->isSelfDevice(fromId)) {
        int min = ui.lineEdit_2->text().toInt();
        int max = ui.lineEdit_3->text().toInt();
               module_->setScreenBitrate(fromId, min * 1000, max * 1000);
      }
    qDebug()<<"onPublishScreenResult "<<result<<","<<fromId.c_str();
}
void Use_Screen::onUnpublishScreenResult(Result result, const DeviceId& fromId) {

}
rtc::DeviceId Use_Screen::getSelectedDeviceId(QListWidget* listw)  {
    QList<QListWidgetItem*> lst = listw->selectedItems();
    if (lst.empty()) {
        return rtc::DeviceId("");
    }
    QListWidgetItem* selItem = lst.at(0);
    QString selId = selItem->data(Qt::UserRole).toString();
    return rtc::DeviceId(selId.toUtf8().data());
}
rtc::ScreenWindow Use_Screen::getSelectedScreenParams()  {
    ScreenWindow selscrn;
    rtc::DeviceId selId = getSelectedDeviceId(ui.lst_screen_lst);
    qDebug() << " getSelectedScreenParams selfId = " <<selId.c_str();
    if (selId.empty()) {
        return selscrn;
    }
    ScreensType items_;
    module_->getScreenWindows(items_);
    for(size_t i=0;i<items_.size();++i){
        if(selId == items_[i].id){
            selscrn = items_[i];
        }
    }

    return selscrn;
}
bool Use_Screen::on_subscribeRemoteScreen(bool sub){
    if (!isAttach()) {
        return false;
    }
    Result ret = Err_Not_Found;
    if (sub) {
        rtc::DeviceId selId = getSelectedDeviceId(ui.lst_screen_lst_remote);
        if (selId.empty()) {
            return false;
        }
        ret = module_->subscribe(selId);
        curRemoteId_ = selId;
        qDebug() << " subscribe screen.... ";
    }
    else {
        module_->unsubscribe(curRemoteId_);
        curRemoteId_ = "";
        qDebug() << " un subscribe screen.... ";
    }
    if (RT_SUCCEEDED(ret)) {
        ButtonChecked(ui.btn_screen_subscribe, sub, (sub ? Utf8Str("取消订阅") : Utf8Str("订阅")));
    }
    return ret;
}
bool Use_Screen::on_publishScreen(bool pub){
    if (!isAttach()) {
        return false;
    }


    Result ret = Err_Not_Found;
    if (pub) {
        rtc::ScreenWindow selscrn = getSelectedScreenParams();
        if (!selscrn.isValid()) {
            return false;
        }
        StreamType type = stream_main;
        int w = ui.lineEdit->text().toInt();
        int h = ui.lineEdit_4->text().toInt();
        int fps = ui.lineEdit_5->text().toInt();

        CameraCapability acap(w,h,fps);
        if(selscrn.type == rtc::st_desktop){
            acap.catx = ui.lineEdit_6->text().toFloat();
            acap.caty = ui.lineEdit_7->text().toFloat();
            acap.catw = ui.lineEdit_8->text().toFloat();
            acap.cath = ui.lineEdit_9->text().toFloat();
        }

        VideoCodec codec = codec_h264;
        selscrn.publishedQualities.setStreamOptions(type, acap, codec);
        ret = module_->publishScreen(selscrn);
        curLocalId_ = selscrn.id;
        qDebug() << Utf8Str(" 发布screen ") << OutputWithRet(ret);
    }
    else {
        curLocalId_ = "";
        ret = module_->unpublishScreen();
        qDebug() << Utf8Str(" 取消发布screen ") << OutputWithRet(ret);
    }
    if (RT_SUCCEEDED(ret)) {
        ButtonChecked(ui.btn_screen_pub, pub, (pub ? Utf8Str("unpubscrn") : Utf8Str("pubscrn")));

    }
    return ret;
}
