/****************************************************************************
** importchapter.cpp
**
**   Created : December 13'th 2007
**        by : Varol Okan
** Copyright : (c) Varol Okan
**   License : GPL v 2.0
**
** This file holds the implementation of the import filter for the chapter 
** markers.
*****************************************************************************/

#include <qfile.h>
#include <qobject.h>
#include <qfiledialog.h>

#include "global.h"
#include "utils.h"
#include "importchapter.h"

namespace Import
{

Chapter::Chapter ( )
{
}

Chapter::~Chapter ( )
{
}

bool Chapter::import ()
{
  QString qsImportFile = QFileDialog::getOpenFileName ( Global::qsCurrentPath, QObject::tr("Chapter files (*.chapter *.CHAPTER *.xml *.XML *.txt *.TXT)"), NULL, QObject::tr("Open Chapter File") );

  // Sanity check .. Did te user choose a new project file ?
  if ( qsImportFile.isNull ( ) )
    return false;

  return readFile ( qsImportFile );
}

bool Chapter::readFile ( QString &fileName )
{
  // Assign the file
  int      t, iType = -1;
  Utils       theUtils;
  QString     line;
  QStringList chapterList;

  QFile projectFile ( fileName );
  if ( ! projectFile.open ( IO_ReadOnly ) )
    return false;
  
  QTextStream chapterStream ( &projectFile );
  // 1 ) 0,0:0:14.0,0:0:22.0
  // 2 ) 00:00:00:00  -> DVDLab  style
  // 3 ) 00:00:00.000 -> Default style

  do {
    line  = chapterStream.readLine ( );
    // here we decide which version we have...
    if ( iType == -1 ) {
      if ( line.find ( ',' ) > -1 )
	iType = 1; // 0,0:0:14.0,0:0:22.0
      else if ( line.contains ( ':' ) == 3 )
	iType = 2; // 00:00:00:00
      else if ( line.find ( '.' ) > -1 )
	iType = 3; // 00:00:00.000
      else if ( line.contains ( ':' ) == 2 )
	iType = 3; // 00:00:00
      else {
	line = chapterStream.readLine ( );
	continue;
      }
    }

    if ( 1 == iType ) {
      QStringList temp = QStringList::split ( ',', line );
      for ( t=0; t<(int)temp.count ( ); t++ )
	chapterList.append ( theUtils.formatChapter ( temp[t] ) );
    }
	else if ( 2 == iType )  {
		if ( line.contains   ( ':' ) == 3 )  {
			t = line.findRev ( ':' );
			line[t] = '.';
		}
		chapterList.append ( theUtils.formatChapter ( line ) );
	}
    else if ( 1  < iType )
      chapterList.append ( theUtils.formatChapter ( line ) );

  } while ( ! chapterStream.atEnd    ( ) );

  projectFile.close ( );
  m_listOfChapters = chapterList;
  return true;
}

QStringList &Chapter::getChapterList ( )
{
  return m_listOfChapters;
}

}; // End of namespace Import
