/* ============================================================
 * File  : player.cpp
 * Author: Stephane Gibault
 * Date  : Sun Feb 4 2007
 * Description :
 *
 * 
 *  (C) 2007 by Stephane Gibault
 *
 * 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 2, 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.
 *
 * ============================================================ */

#include <QtGui>
#include "mainfrm.h"

void mainfrm::player_open_video(QString pathvideo)
{
        if ( mplayerProcess.state() == QProcess::Starting || mplayerProcess.state() == QProcess::Running )
	{
		//mplayerProcess.write("quit 0 \n");
		mplayerProcess.kill();
		mplayerProcess.waitForFinished(1000);	
		mplayer_timer->stop();
        }
	wg_int_004 = 0;
	slider_player->setValue(0);
	slider_player->setMaximum(hdl_current_media->wl_duree.toInt());
       	QStringList args;
        args << "-slave";
        args << "-osdlevel" << "0";
        args << "-noquiet";
	args << "-zoom";
	//args << "-double";
	//args << "-tsprobe" << "1";
        args << "-wid" << QString::number(frame_player_media->winId()); //
	args << "-vo" << "gl:nomanyfmts";
	args << pathvideo;

        if ( hdl_current_media->wl_sub_path != "" )
	{
		args << "-sub" << hdl_current_media->wl_sub_path;
        }
	args << "-vf" << "pp=lb";
        //args << "-keepaspect";
	args << "-nokeepaspect";
	args << "-framedrop";
        //args << "-cache" << QString::number( 1024 );
        /*args << "-cache-min" << QString::number( 99 );*/
        //args << "-cache-seek-min" << QString::number( 99 );
        args << "-loop" << "0";
        mplayerProcess.setProcessChannelMode(QProcess::MergedChannels);
      	mplayerProcess.start("mplayer", args);
      	if(!mplayerProcess.waitForStarted(3000))
      	{
		QMessageBox::information(this, name_application, tr("Impossible de demarrer mplayer. Est t il installe correctement dans /usr/bin ?"));
	}
	else
	{
		wg_string_005 = pathvideo;
                player_isplaying = true;
                bt_player_play_stop->setChecked(true);
                mplayer_timer->start(1000);
		QString mycom = "hue " + QString::number(hdl_current_media->hue) + " 1 \n";
		mplayerProcess.write(mycom.toUtf8());
		mycom = "brightness " + QString::number(hdl_current_media->lumiere) + " 1 \n";
		mplayerProcess.write(mycom.toUtf8());
		mycom = "contrast " + QString::number(hdl_current_media->contraste) + " 1 \n";
		mplayerProcess.write(mycom.toUtf8());
		mycom = "saturation " + QString::number(hdl_current_media->saturation) + " 1 \n";
		mplayerProcess.write(mycom.toUtf8());
        }
}

void mainfrm::player_start_seek()
{
	oldseek = slider_player->value();
	mplayer_timer->stop();
}

void mainfrm::player_move_seek(int)
{
	/*mplayerProcess.write("mute \n");
	mplayerProcess.write("pause \n");
	QString mycom = "seek " + QString::number(position) + " 2\n";
	mplayerProcess.write( mycom.toUtf8() );
	mplayerProcess.write("mute \n");
	mplayer_timer->start(10);*/
}

void mainfrm::player_stop_seek()
{
	if ( oldseek < slider_player->value() )
	{
		wg_int_004 = 1;
	}
	else
	{
		wg_int_004 = 2;
	}
	//mplayerProcess.write("mute \n");
	//mplayerProcess.write("pause \n");
	QString mycom = "pausing_keep seek " + QString::number(slider_player->value()) + " 2 \n";
	mplayerProcess.write( mycom.toUtf8(),mycom.length() );
	//mplayerProcess.write("mute \n");
	mplayer_timer->start(1000);
}

void mainfrm::f_init_effects()
{
	slider_bri->setValue(0);
	slider_con->setValue(0);
	slider_sat->setValue(0);
}

void mainfrm::player_bri(int value)
{
	if (must_update == 1 )
	{
		QString mycom = "brightness " + QString::number(value) + " 1 \n";
		mplayerProcess.write(mycom.toUtf8());
	}
}

void mainfrm::player_con(int value)
{
	if (must_update == 1 )
	{
		QString mycom = "contrast " + QString::number(value) + " 1 \n";
		mplayerProcess.write(mycom.toUtf8());
	}
}

void mainfrm::player_sat(int value)
{
	if (must_update == 1 )
	{
		QString mycom = "saturation " + QString::number(value) + " 1 \n";
		mplayerProcess.write(mycom.toUtf8());
	}
}

void mainfrm::player_current_percent()
{
	mplayerProcess.write("get_time_pos \n");
}

void mainfrm::player_play_video()
{
	if ( mplayerProcess.state() == QProcess::Starting || mplayerProcess.state() == QProcess::Running )
	{
		if ( player_isplaying == true )
		{
			mplayerProcess.write("pause \n");
			mplayer_timer->stop();
			player_isplaying = false;
			slider_player->setDisabled(true);
			bt_avance_player->setDisabled(true);
			bt_recul_player->setDisabled(true);
		}
		else
		{
			mplayerProcess.write("pause \n");
			mplayer_timer->start(1000);
			player_isplaying = true;
			slider_player->setEnabled(true);
			bt_avance_player->setEnabled(true);
			bt_recul_player->setEnabled(true);
		}
	}
}

void mainfrm::player_read_stdout()
{
	//if (mplayerProcess.canReadLine())
        //{
		QByteArray buffer(mplayerProcess.readLine());

                if (buffer.startsWith("ANS_TIME_POSITION"))
                {
                	buffer.remove(0, 18);
                        buffer.replace(QByteArray("'"), QByteArray(""));
                        buffer.replace(QByteArray(" "), QByteArray(""));
                        buffer.replace(QByteArray("\n"), QByteArray(""));
                        buffer.replace(QByteArray("\r"), QByteArray(""));
			player_position = buffer.toFloat();
			if ( wg_int_004 == 0 )
			{
				slider_player->setValue(player_position);
			}
			else
			{
				if ( wg_int_004 == 1 )
				{
					if ( slider_player->value() < player_position )
					{
						slider_player->setValue(player_position);
						wg_int_004 = 0;
					}
				}
				else
				{
					if ( slider_player->value() > player_position )
					{
						slider_player->setValue(player_position);
						wg_int_004 = 0;
					}
				}
			}
                }
	//}
}

void mainfrm::player_avance()
{
	//mplayerProcess.write("mute \n");
	//mplayerProcess.write("pause \n");
	mplayerProcess.write("pausing_keep seek +10 0 \n");
	//mplayerProcess.write("mute \n");
}

void mainfrm::player_recule()
{
	//mplayerProcess.write("mute \n");
	//mplayerProcess.write("pause \n");
	mplayerProcess.write("pausing_keep seek -10 0 \n");
	//mplayerProcess.write("mute \n");
}

void mainfrm::player_mute()
{
	mplayerProcess.write("mute\n");
	//mplayerProcess.write("pause \n");
}

void mainfrm::player_close()
{
	if ( player_isplaying == true )
	{
		mplayerProcess.write("pause \n");
		mplayer_timer->stop();
		player_isplaying = false;
	}
	//mplayerProcess.write("quit 0 \n");
	mplayerProcess.kill();
	lst_chapters->selectAll();
	lst_chapters_2->selectAll();
	QList<QListWidgetItem*> lst_chapitres = lst_chapters->selectedItems();
	QList<QListWidgetItem*> lst_chapitres_2 = lst_chapters_2->selectedItems();
	int wl_int_001 = 0;

	for (wl_int_001 = 0; wl_int_001 < lst_chapitres.size(); ++wl_int_001) 
	{
		hdl_current_media->chapitres[wl_int_001] = lst_chapitres.at(wl_int_001)->text();
		hdl_current_media->icones_chapitres[wl_int_001] = lst_chapitres_2.at(wl_int_001)->icon();
	}
	hdl_current_media->nbre_chapitres = wl_int_001;
	lst_chapters->clear();
	lst_chapters_2->clear();
	frame_chapitrage->hide();
	//frame_chapitrage->lower();
	//frame_editor->show();
	//mask_interface->show();
	//frame_medias->show();
}

void mainfrm::player_add_chapter()
{
	// *** AJOUTER UN CHAPITRE MANUELEMENT ***
	QTime n(0, 0, 0);
	QTime t;
	t = n.addSecs(slider_player->value());  

	if ( t.toString() != "00:00:00" )
	{
		QList<QListWidgetItem *> existchap = lst_chapters->findItems( t.toString("hh:mm:ss"), Qt::MatchExactly );

		if ( existchap.count() == 0 )
		{
			QPixmap wlpixmap = QPixmap::grabWindow(this->winId(), frame_chapitrage->geometry().x()+frame_support_player->geometry().x()+frame_player_media->geometry().x(), frame_chapitrage->geometry().y()+frame_support_player->geometry().y()+frame_player_media->geometry().y()+smenuBar->height(),frame_player_media->width(),frame_player_media->height());
			QListWidgetItem *item = new QListWidgetItem(lst_chapters);
			item->setIcon(QIcon(wlpixmap));
			item->setText(t.toString("hh:mm:ss"));
			lst_chapters->sortItems(Qt::AscendingOrder);

			QListWidgetItem *item2 = new QListWidgetItem(lst_chapters_2);
			item2->setIcon(QIcon(wlpixmap));
			t = n.addSecs(player_position);  
			item2->setText(t.toString("hh:mm:ss"));
			lst_chapters_2->sortItems(Qt::AscendingOrder);
		}
	}
}

void mainfrm::player_go_chapter(QString position)
{
	mplayer_timer->stop();

	oldseek = slider_player->value();

	player_isplaying = false;
	/*if ( player_isplaying == true )
	{
		mplayerProcess.write("pause \n");
	}*/

	QTime t;
	t = QTime::fromString(position,"hh:mm:ss");
	int timego = t.second() + (t.minute()*60) + (t.hour() * 3600);
	QString mycom;

	mycom = "pausing_keep seek " + QString::number(timego) + " 2\n";
	mplayerProcess.write( mycom.toUtf8() );
	bt_player_play_stop->setChecked(true);

	if ( oldseek < timego )
	{
		wg_int_004 = 1;
	}
	else
	{
		wg_int_004 = 2;
	}
	slider_player->setValue(timego);
	mplayer_timer->start(1000);
	player_isplaying = true;
	bt_avance_player->setEnabled(true);
	bt_recul_player->setEnabled(true);
}

void mainfrm::player_auto_chapter()
{
	// *** CALCUL CHAPITRAGE AUTOMATIQUE ***
	wg_int_001 = (hdl_current_media->wl_duree.toInt() / 60) / combo_autochapter->value();
	if ( wg_int_001 > 0 )
	{
		wg_int_002 = 0;
		lst_chapters->clear();
		lst_chapters_2->clear();
		if ( player_isplaying == true )
		{
			mplayerProcess.write("pause \n");
			mplayer_timer->stop();
			player_isplaying = false;
			bt_player_play_stop->setChecked(false);
			bt_avance_player->setDisabled(true);
			slider_player->setDisabled(true);
			bt_recul_player->setDisabled(true);
		}

		QTime n(0, 0, 0);
		QTime t(0, 0, 0);

		while ( wg_int_002 < wg_int_001 )
		{
			n = t;
			QListWidgetItem *item = new QListWidgetItem(lst_chapters);
			item->setIcon(QIcon(QIcon(":/Interface/Interface/reload.png")));
			t = n.addSecs(combo_autochapter->value() * 60);  
			item->setText(t.toString("hh:mm:ss"));

			QListWidgetItem *item2 = new QListWidgetItem(lst_chapters_2);
			item2->setIcon(QIcon(QIcon(":/Interface/Interface/reload.png")));
			item2->setText(t.toString("hh:mm:ss"));

			wg_int_002++;
		}

		// *** GENERATION DES MINIATURES ***
		player_auto_chapter_thumb();
	}
}

void mainfrm::player_auto_chapter_thumb()
{
	wg_int_003=0;
	QString programf = "ffmpegthumbnailer";
	QStringList argumentsf;
	QListWidgetItem *mywidget = new QListWidgetItem;

	while ( wg_int_003 < wg_int_002 )
	{
		mywidget = lst_chapters->item(wg_int_003);
		//QTime t;
		//t = QTime::fromString(mywidget->text(),"hh:mm:ss");
		//int timego = t.second() + (t.minute()*60) + (t.hour() * 3600);

		// *** RECUPERATION DE LA MINIATURE DU CHAPITRE ***
		argumentsf.clear();
		argumentsf << "-i";
		argumentsf << wg_string_005;
		argumentsf << "-s";
		argumentsf << "500";
		argumentsf << "-t";
		argumentsf << mywidget->text();
		argumentsf << "-o";
		argumentsf << path_project + "/DVD/TEMP/MI" + QString::number(wg_int_003) + ".jpg";

	      	proc_ffmpeg.setProcessChannelMode(QProcess::MergedChannels);
		proc_ffmpeg.start(programf,argumentsf);

		proc_ffmpeg.waitForFinished(-1);

		mywidget->setIcon(QIcon(path_project + "/DVD/TEMP/MI" + QString::number(wg_int_003) + ".jpg"));
		mywidget = lst_chapters_2->item(wg_int_003);
		mywidget->setIcon(QIcon(path_project + "/DVD/TEMP/MI" + QString::number(wg_int_003) + ".jpg"));
		wg_int_003++;
	}
}

// ************************************
// *** CAPTURE DE L'IMAGE DU PLAYER ***
// ************************************

void mainfrm::player_capture()
{
	wg_pix_001 = QPixmap::grabWindow(this->winId(), frame_support_player->geometry().x()+frame_player_media->geometry().x(), frame_support_player->geometry().y()+frame_player_media->geometry().y()+smenuBar->height(),frame_player_media->width(),frame_player_media->height());
	QString wmyimg = QFileDialog::getSaveFileName(this, tr("Sauvegarder l'image"), path_capture, tr("Image (*.jpg)"));
       	if ( wmyimg.isNull() )
       	{
		return;
       	}
	else
	{
   		wg_int_001 = wmyimg.lastIndexOf( '/' );
    		if ( wg_int_001 != -1 )
    		{
        		path_capture = wmyimg.mid(0,wg_int_001);
    		}

		if ( wmyimg.right(4) != ".jpg" )
		{
			wmyimg = wmyimg + ".jpg";
		}
		wg_pix_001.save(wmyimg,"JPEG");
	}
}

