/*
    This file is part of the kholidays library.

    Copyright 2010 John Layt <john@layt.net>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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 Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "holidayparserdriverplanold_p.h"

#include <QStringList>
#include <QFileInfo>

#include <KCalendarSystem>
#include <kdebug.h>

#include "holiday_p.h"

// Extern for C implementation of parser generated by Bison/Flex
extern "C" {
#ifdef Q_OS_WIN32
    KHOLIDAYS_EXPORT char *parse_holidays( const char *, int year, short force );
#else
    char *parse_holidays( const char *, int year, short force );
#endif

    struct holiday {
        char            *string;
        int             color;
        unsigned short  dup;
        holiday         *next;
    };

#ifdef Q_OS_WIN32
    KHOLIDAYS_EXPORT extern struct holiday holidays[366];
#else
    extern struct holiday holidays[366];
#endif
}

using namespace KHolidays;

HolidayParserDriverPlanOld::HolidayParserDriverPlanOld( const QString &planFilePath )
                           :HolidayParserDriver( planFilePath )
{
    parseMetadata();
}

HolidayParserDriverPlanOld::~HolidayParserDriverPlanOld()
{
}

void HolidayParserDriverPlanOld::error( const QString &errorMessage )
{
    kDebug() << errorMessage;
}

void HolidayParserDriverPlanOld::parse()
{
    // We only parse for the Gregorian calendar
    setParseCalendar( "gregorian" );
    // Set the parse start/end years from the request start/end dates
    setParseStartEnd();

    QDate thisDate;

    // Generate all events for this calendar in the requested year(s)
    for ( m_parseYear = m_parseStartYear; m_parseYear <= m_parseEndYear; ++m_parseYear ) {

        QDate parseYearStart;
        m_parseCalendar->setDate( parseYearStart, m_parseYear, 1, 1 );

        // Parser takes a 2-digit year assumed to be in range 1950-2050
        parse_holidays( QFile::encodeName( m_filePath ), m_parseYear - 1900, 1 );

        // Add this years holidays to holiday list
        for ( int i = 0; i < 366; ++i ) {
            struct holiday *hd = &::holidays[i];
            thisDate = parseYearStart.addDays(i);
            // Only add holidays if they fall inside requested range
            if ( thisDate >= m_requestStart && thisDate <= m_requestEnd ) {
                while ( hd ) {
                    if ( hd->string ) {
                        Holiday holiday;
                        holiday.d->mObservedDate = thisDate;
                        holiday.d->mText = QString::fromUtf8( hd->string );
                        holiday.d->mShortText = holiday.d->mText;
                        if ( hd->color == 2 || hd->color == 9 ) {
                            holiday.d->mDayType = Holiday::NonWorkday;
                        } else {
                            holiday.d->mDayType = Holiday::Workday;
                        }
                        m_resultList.append( holiday );
                    }
                    hd = hd->next;
                }
            }
        }
    }
}

void HolidayParserDriverPlanOld::parseMetadata()
{
    // metadata is encoded in filename in form holiday_<region>_<type>_<language>_<name>
    // with region, type and language sub groups separated by -, and with name optional
    m_fileCountryCode.clear();
    m_fileLanguageCode.clear();
    m_fileName.clear();
    m_fileDescription.clear();

    QFileInfo file( m_filePath );
    if ( file.exists() ) {
        QStringList metadata = file.fileName().split('_');
        if ( metadata[0] == "holiday" && metadata.count() > 2 ) {
            m_fileCountryCode = metadata[1].toUpper();
            QStringList language = metadata[2].split('-');
            m_fileLanguageCode = language[0];
            if ( language.count() > 1 ) {
                m_fileLanguageCode.append( '_' ).append( language[1].toUpper() );
            }
            if ( metadata.count() > 3 ) {
                m_fileName = metadata[3];
            }
        }
    }
}
