/*
* Copyright (C) 2019 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, 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 <http://www.gnu.org/licenses/&gt;.
*
*/
#include "noticeAlarm.h"
#include "ui_noticeAlarm.h"
#include <QPalette>
#include <QSqlTableModel>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QDebug>
#include <QPainterPath>
#include <X11/Xlib.h>
#include "clockentitydao.h"
#include "xatom-helper.h"
#include "mediaplayerpool.h"
#include "gsettingsubject.h"
#include <math.h>
#include <QThread>

extern void qt_blurImage(QImage &blurImage, qreal radius, bool quality, int transposed);
/**
 * @brief
 * @param
 * @param      num 闹钟序号 倒计时传-1
 *
 * @return 返回说明
 */
Natice_alarm::Natice_alarm(int close_time, int num, QWidget *parent , QString clockId) :
    QWidget(parent),
    ui(new Ui::Natice_alarm),
    timer_value(close_time),
    num_flag(num),
    m_clockId(clockId)
{
    ui->setupUi(this);
    m_musicPlayer = new MMediaPlayer(this);
    m_playList = new MMediaPlaylist(m_musicPlayer);
    m_playList->setPlaybackMode(MMediaPlaylist::CurrentItemInLoop);
    Qt::WindowFlags m_flags = windowFlags();
    this->setWindowFlags(m_flags | Qt::WindowStaysOnTopHint);

    // 添加窗管协议
    XAtomHelper::setStandardWindowHint(this->winId());
    m_selectBtnUtil = new SelectBtnUtil();
    //响铃提示
    this->setWindowTitle(tr("Ring prompt"));
    this->setWindowIcon(QIcon::fromTheme("kylin-alarm-clock"));
    //多少秒后自动关闭
    ui->autoCloseTime->setAlignment(Qt::AlignRight);
    QPalette pa;
    pa.setColor(QPalette::WindowText,Qt::gray);
    ui->autoCloseTime->setPalette(pa);

    //this->setProperty("blurRegion", QRegion(QRect(1, 1, 1, 1)));
    //保存一个多少秒后关闭，用于稍后提醒的显式
    timer_value2 = timer_value;
    //右上角关闭
    connect(ui->closeTitleBtn, SIGNAL(clicked()), this, SLOT(set_dialog_close()) );
    //稍后提醒
    connect(ui->remindLateBtn, SIGNAL(clicked()), this, SLOT(show_again()) );
    //进行 剩余秒数显示 的定时
    timer = new QTimer();
    //剩余秒 减1
    connect(timer, SIGNAL(timeout()), this, SLOT(close_music()));
    timer->setInterval(1000);

    timer_xumhuan = new QTimer();
    //稍后提醒的定时
    connect(timer_xumhuan, SIGNAL(timeout()), this, SLOT(ring()));
    timer_xumhuan->setInterval(1000);
    model_clock = clock_sql::getClockTable(this);
    natice_init();
    QPalette palette1 = ui->closeTitleBtn->palette();
    QColor ColorPlaceholderText1(255,255,255,0);
    QBrush brush;
    brush.setColor(ColorPlaceholderText1);
    ui->closeTitleBtn->setPalette(palette1);

    ui->closeTitleBtn->setIcon(QIcon::fromTheme("window-close-symbolic"));
    ui->closeTitleBtn->setProperty("isWindowButton", 0x2);
    ui->closeTitleBtn->setProperty("useIconHighlightEffect", 0x8);
    ui->closeTitleBtn->setFlat(true);
    //启用主题框架不需要代码
    ui->titleIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24));
    //    主题框架1.0.6-5kylin2

    //配置重要按钮 关闭
    ui->remindLateBtn->setProperty("isImportant", true);
    ui->closeTitleBtn->setFocusPolicy(Qt::NoFocus);
    //数据库
    model_setup = clock_sql::getSetupTable(this);
    //倒计时初始化无稍后提醒
    if(num_flag < 0){
        hideRemindBtn();
    }
    settingsStyle();
}

void Natice_alarm::settingsStyle()
{

    GsettingSubject * subject = GsettingSubject::getInstance();
    connect(subject,&GsettingSubject::fontChanged, this,[=](int size){
        this->CURRENT_FONT_SIZE=size;
        this->updateFront(size);
    });
    connect(subject,&GsettingSubject::iconChnaged, this,[=](){
        ui->titleIcon->setPixmap(QIcon::fromTheme("kylin-alarm-clock").pixmap(24,24));
    });
    subject->iniFontSize();

}

void Natice_alarm::updateFront(int size)
{
    double font = 1.15;
    int pointSize = round(font*size);
    updateLabelFront(ui->titleLabel,pointSize);
    updateLabelFront(ui->timeEndInfo,pointSize);
    updateLabelFront(ui->autoCloseTime,pointSize);
    QFont tempFont;
    tempFont.setPixelSize(pointSize);
    ui->remindLateBtn->setFont(tempFont);
}
void Natice_alarm::updateLabelFront(QLabel *label, int size)
{
    QString styleSheet = "font-size:";
    styleSheet.append(QString::number(size)).append("px;");
    label->setStyleSheet(styleSheet);
}

Natice_alarm::~Natice_alarm()
{
    delete timer;
    delete timer_xumhuan;
    delete ui;
}
/**
 * @brief 初始化铃声
 * @param
 * @param
 *
 * @return 返回说明
 */
void Natice_alarm::natice_init()
{
    if(num_flag >= 0)
    {
        auto sqlQuery = ClockEntityDao::getClockByPK(m_clockId);
        //更新闹钟名称
        QString info = model_clock->index(num_flag, 0).data().toString();
        info = Utils::changeNumToStr(info.toInt());
        info = info.append(":");
        info = info.append(Utils::changeNumToStr(model_clock->index(num_flag, 1).data().toInt()));
        info = info.append(" ");
        QString clockName = model_clock->index(num_flag, 13).data().toString();
        int sizeLimit = 3;
        if(clockName.length()>sizeLimit){
            //名字超长
            ui->timeEndInfo->setToolTip(info+clockName);
            clockName = clockName.left(sizeLimit);
            clockName = clockName+"...";
        }
        info = info.append(clockName);
        ui->timeEndInfo->setText(info);
        //稍后提醒逻辑
        QString remindLate = model_clock->index(num_flag, 15).data().toString();
        if(remindLate=="none"||remindLate==tr("none")){
            hideRemindBtn();
        }else{
            showRemindBtn();
        }
    } else {
        //倒计时
        ui->timeEndInfo->setText(tr("Time out")+"！");
    }
}

void Natice_alarm::closeMusic()
{

}
//重新加载最新音乐
void Natice_alarm::refreshMusic()
{
    QSqlTableModel *model = new QSqlTableModel(this);
    model->setTable("clock");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    model_setup->select();
    QString bellId="";
    if(num_flag >= 0){
        auto sqlQuery = ClockEntityDao::getClockByPK(m_clockId);
        bellId = sqlQuery.value( 2).toString();
    } else {
        bellId = model_setup->index(0, 1).data().toString();
    }
    QString noneId = m_selectBtnUtil->getBellIdByNameEn("none");
    if(bellId!=noneId){
        QString path = m_selectBtnUtil->getBellPathById(bellId);
        m_playList->clear();
        m_playList->addMedia(QUrl::fromLocalFile(path));
        m_musicPlayer->setPlaylist(m_playList);
        int muteOn = model_setup->index(0, 0).data().toInt();
        if(muteOn){
            qDebug()<<"dbq-静音";
        }else{
            m_musicPlayer->setVolume(  100 );
            m_musicPlayer->play();
        }
    }
}

void Natice_alarm::hideRemindBtn()
{
    ui->widget_3->hide();
    this->setFixedSize(288,90);

}

void Natice_alarm::showRemindBtn()
{
    ui->widget_3->show();
    this->setFixedSize(288,120);
}

void Natice_alarm::playMusic()
{
    timer_value =  timer_value2;
    m_musicPlayer->setVolume(100);
    timer->start();
    show();
    refreshMusic();
}

//窗口关闭
/**
 * @brief 铃声、窗体、timer关闭
 * @param
 * @param
 *
 * @return 返回说明
 */
void Natice_alarm::set_dialog_close()
{
    timer->stop();
    m_musicPlayer->stop();
    if(num_flag >= 0)
    {
        this->close();
    }else{ //倒计时的隐藏不关闭
        this->hide();
    }
}
//关闭音乐
/**
 * @brief 剩余时间读秒 全关闭
 * @param
 * @param
 *
 * @return 返回说明
 */
void Natice_alarm::close_music()
{
    if (timer_value == 0) {
        set_dialog_close();
    }
    timer_value--;
    ui->autoCloseTime->setText(QString::number(timer_value)+tr(" Seconds to close"));
}
//绘制背景
// Draw background
void Natice_alarm::paintEvent(QPaintEvent *event)
{
//    if (!full_flag) {
//        return;
//    }

    Q_UNUSED(event);
    QPainter p(this);
    p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
    QPainterPath rectPath;
    rectPath.addRect(this->rect());
    p.fillPath(rectPath,palette().color(QPalette::Base));

}
//再次弹出
//Eject again
void Natice_alarm::show_again()
{
    this->hide();
    //刷新数据
    model_setup->select();
    QString info = model_clock->index(num_flag, 15).data().toString();
    int remind = getRemindStatusByName(info);
    if (remind == 1) {
        ring_num = 300;
    } else if(remind == 2) {
        ring_num = 600;
    } else if(remind == 3) {
        ring_num = 1200;
    } else if(remind == 4) {
        ring_num = 1800;
    } else if(remind == 5) {
        ring_num = 3600;
    }
    timer_value =  timer_value2;
    timer_xumhuan->start();
    timer->stop();
    m_musicPlayer->stop();
}

int Natice_alarm::getRemindStatusByName(QString name)
{
    int status = 0;
    if(name.compare("none") == 0 || name.compare("不需要") == 0){
        status = 0;
    }else if(name.compare("five mins late") == 0 || name.compare("5分钟后") == 0){
        status = 1;
    }else if(name.compare("ten mins late") == 0 || name.compare("10分钟后") == 0){
        status = 2;
    }else if(name.compare("twenty mins late") == 0 || name.compare("20分钟后") == 0){
        status = 3;
    }else if(name.compare("thirsty mins late") == 0 || name.compare("30分钟后") == 0){
        status = 4;
    }else if(name.compare("one hour late") == 0 || name.compare("1小时后") == 0){
        status = 5;
    }
    return status;
}
//响铃
//Ring a bell 每一秒减一
void Natice_alarm::ring()
{
    ring_num--;
    if (ring_num == 0) {
        timer_xumhuan->stop();
        if(num_flag >= 0){
            bool result = ClockEntityDao::checkClockExist(m_clockId);
            if(result){
                natice_init();
                this->show();
                timer->start();
                refreshMusic();
            }else{
                qDebug()<<"dbq-闹钟被删-啥也不做";
            }
        }else{
            natice_init();
            this->show();
            timer->start();
            refreshMusic();
        }

    }
}


//bool Natice_alarm::eventFilter(QObject *watched, QEvent *event)
//{
//    if(watched == ui->widget && event->type() == QEvent::Paint)
//    {
//        showPaint(); //响应函数
//    }
//    return QWidget::eventFilter(watched,event);
//}

////实现响应函数
//void Natice_alarm::showPaint()
//{
//    QPainter p(ui->widget);
//    p.setRenderHint(QPainter::Antialiasing);  // 反锯齿;
//    QPainterPath rectPath;
//    rectPath.addRoundedRect(ui->widget->rect().adjusted(6, 6, -6, -6), 6, 6);

//    // 画一个黑底
//    QPixmap pixmap(ui->widget->rect().size());
//    pixmap.fill(Qt::transparent);
//    QPainter pixmapPainter(&pixmap);
//    pixmapPainter.setRenderHint(QPainter::Antialiasing);
//    pixmapPainter.setPen(Qt::transparent);
//    pixmapPainter.setBrush(Qt::gray);
//    pixmapPainter.drawPath(rectPath);
//    pixmapPainter.end();

//    // 模糊这个黑底
//    QImage img = pixmap.toImage();
//    qt_blurImage(img, 10, false, false);

//    // 挖掉中心
//    pixmap = QPixmap::fromImage(img);
//    QPainter pixmapPainter2(&pixmap);
//    pixmapPainter2.setRenderHint(QPainter::Antialiasing);
//    pixmapPainter2.setCompositionMode(QPainter::CompositionMode_Clear);
//    pixmapPainter2.setPen(Qt::transparent);
//    pixmapPainter2.setBrush(QColor(0,0,0));
//    pixmapPainter2.drawPath(rectPath);

//    // 绘制阴影
//    p.drawPixmap(ui->widget->rect(), pixmap, pixmap.rect());
//    p.setOpacity(0.9);
//    // 绘制一个背景
//    p.save();
//    p.fillPath(rectPath,palette().color(QPalette::Base));
//    p.restore();
//}


void Natice_alarm::closeEvent(QCloseEvent *event)
{
    timer->stop();
    m_musicPlayer->stop();
    if(num_flag >= 0)
    {
        event->accept();//接受
        this->close();
    }else{
        event->ignore();//忽视
        this->hide();
    }
}
