#include "ymorpherethread.h"
#include <QDate>
void YMorphereThread::setParam(QMap<QString, QString> mapParam)
{
    m_mapParam = mapParam;
    parseParam();
}

void YMorphereThread::setMutex(QMutex *mutex)
{
    this->mutex = mutex;
}

void YMorphereThread::setID(int nID)
{

}

void YMorphereThread::setDataAlgorithmInterface(DataAlgorithmInterface* DAInterface)
{
    m_pDAInterface = DAInterface;
}

void YMorphereThread::setMemory(QMap <QString, int> *threadMap)
{
    m_pmapResult = threadMap;
}

QMap<QString, int> YMorphereThread::getResult()
{
    return m_mapResult;
}


void YMorphereThread::clearpResult()
{
    m_pmapResult->clear();
}

void YMorphereThread::clearResult()
{
    m_mapResult.clear();
}



QString YMorphereThread::getWeeksInMonth(unsigned int _nDate)
{

    QDate qToday(_nDate/10000, (_nDate/100)%100, _nDate%100);
    if(!qToday.isValid())
        return "inVaildDate";

    QDate qTodayFirstDay = QDate(qToday.year(), qToday.month(), 1);
    QDate qTodayLastDay = QDate(qToday.year(), qToday.month(), qToday.daysInMonth());

    int thisFirstDayofWeek = qTodayFirstDay.dayOfWeek();
    int thisLastDayofWeek = qTodayLastDay.dayOfWeek();
    int thisLastDay = qTodayLastDay.daysInMonth();
    int week = 0;
    int firstWeekDays = (WEEK - thisFirstDayofWeek) + 1;
    QString strWeek = "W";

    if(thisFirstDayofWeek < FRIDAY)
    {
        week = 1;
    }
    else
    {
        week = 0;
    }

    if((firstWeekDays < qToday.day()) && (qToday.day() <= (thisLastDay - thisLastDayofWeek)))
    {
        week = week + ((qToday.day() - firstWeekDays + WEEK - 1)/WEEK);
    }
    else if((firstWeekDays >= qToday.day()))
    {
        if(thisFirstDayofWeek >= FRIDAY)
        {

            const int DAYS_IN_WEEK = 7;
            qToday = qToday.addMonths(-1);
            int DaysInMonth = qToday.daysInMonth();
            QDate FirstDayOfMonth = qToday;
            FirstDayOfMonth.setDate(qToday.year(), qToday.month(), 1);

            int WeekCount = DaysInMonth / DAYS_IN_WEEK;
            int DaysLeft = DaysInMonth % DAYS_IN_WEEK;
            if (DaysLeft > 0) {
               WeekCount++;
               // Check if the remaining days are split on two weeks
               if (FirstDayOfMonth.dayOfWeek() + DaysLeft - 1 > DAYS_IN_WEEK)
                  WeekCount++;
            }
            week = WeekCount;
        }
    }
    else
    {
        if(thisLastDayofWeek < THURSDAY)
        {
            week = 1;
            qToday = qToday.addMonths(1);
        }
        else
        {
            week = week + ((qToday.day() - firstWeekDays + WEEK - 1)/WEEK);
        }
    }

    strWeek += qToday.toString("yyyyMM");
    strWeek += QString::number(week);
    return strWeek;
}
