/*****************************************************************************
 * streamout.cpp : wxWindows plugin for vlc
 *****************************************************************************
 * Copyright (C) 2000-2001 VideoLAN
 * $Id: streamout.cpp,v 1.2 2003/03/22 11:21:58 gbazin Exp $
 *
 * Authors: Gildas Bazin <gbazin@netcourrier.com>
 *
 * 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 of the License, 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
#include <stdlib.h>                                      /* malloc(), free() */
#include <errno.h>                                                 /* ENOMEM */
#include <string.h>                                            /* strerror() */
#include <stdio.h>

#include <vlc/vlc.h>

#ifdef WIN32                                                 /* mingw32 hack */
#undef Yield
#undef CreateDialog
#endif

/* Let vlc take care of the i18n stuff */
#define WXINTL_NO_GETTEXT_MACRO

#include <wx/wxprec.h>
#include <wx/wx.h>
#include <wx/notebook.h>
#include <wx/textctrl.h>
#include <wx/combobox.h>
#include <wx/spinctrl.h>
#include <wx/statline.h>

#include <vlc/intf.h>

#include "wxwindows.h"

#ifndef wxRB_SINGLE
#   define wxRB_SINGLE 0
#endif

enum
{
    FILE_ACCESS_OUT = 0,
    HTTP_ACCESS_OUT,
    UDP_ACCESS_OUT,
    RTP_ACCESS_OUT
};

enum
{
    TS_ENCAPSULATION = 0,
    PS_ENCAPSULATION,
    AVI_ENCAPSULATION,
    OGG_ENCAPSULATION
};

/*****************************************************************************
 * Event Table.
 *****************************************************************************/

/* IDs for the controls and the menu commands */
enum
{
    Notebook_Event = wxID_HIGHEST,
    MRL_Event,

    FileBrowse_Event,
    FileName_Event,

    AccessType_Event,
    AccessRadio1_Event, AccessRadio2_Event,
    AccessRadio3_Event, AccessRadio4_Event,
    NetPort_Event,
    NetAddr_Event,

    EncapsulationRadio1_Event, EncapsulationRadio2_Event,
    EncapsulationRadio3_Event, EncapsulationRadio4_Event,
};

BEGIN_EVENT_TABLE(SoutDialog, wxDialog)
    /* Button events */
    EVT_BUTTON(wxID_OK, SoutDialog::OnOk)
    EVT_BUTTON(wxID_CANCEL, SoutDialog::OnCancel)

    /* Events generated by the access output panel */
    EVT_RADIOBUTTON(AccessRadio1_Event, SoutDialog::OnAccessTypeChange)
    EVT_RADIOBUTTON(AccessRadio2_Event, SoutDialog::OnAccessTypeChange)
    EVT_RADIOBUTTON(AccessRadio3_Event, SoutDialog::OnAccessTypeChange)
    EVT_RADIOBUTTON(AccessRadio4_Event, SoutDialog::OnAccessTypeChange)
    EVT_TEXT(FileName_Event, SoutDialog::OnFileChange)
    EVT_BUTTON(FileBrowse_Event, SoutDialog::OnFileBrowse)
    EVT_TEXT(NetPort_Event, SoutDialog::OnNetChange)
    EVT_SPINCTRL(NetPort_Event, SoutDialog::OnNetChange)
    EVT_TEXT(NetAddr_Event, SoutDialog::OnNetChange)
 
    /* Events generated by the encapsulation panel */
    EVT_RADIOBUTTON(EncapsulationRadio1_Event,
                    SoutDialog::OnEncapsulationChange)
    EVT_RADIOBUTTON(EncapsulationRadio2_Event,
                    SoutDialog::OnEncapsulationChange)
    EVT_RADIOBUTTON(EncapsulationRadio3_Event,
                    SoutDialog::OnEncapsulationChange)
    EVT_RADIOBUTTON(EncapsulationRadio4_Event,
                    SoutDialog::OnEncapsulationChange)

END_EVENT_TABLE()

/*****************************************************************************
 * Constructor.
 *****************************************************************************/
SoutDialog::SoutDialog( intf_thread_t *_p_intf, Interface *_p_main_interface ):
    wxDialog( _p_main_interface, -1, _("Stream Output"), wxDefaultPosition,
             wxDefaultSize, wxDEFAULT_FRAME_STYLE )
{
    /* Initializations */
    p_intf = _p_intf;
    p_main_interface = _p_main_interface;

    /* Create a panel to put everything in */
    wxPanel *panel = new wxPanel( this, -1 );
    panel->SetAutoLayout( TRUE );

    /* Create MRL combobox */
    wxBoxSizer *mrl_sizer_sizer = new wxBoxSizer( wxHORIZONTAL );
    wxStaticBox *mrl_box = new wxStaticBox( panel, -1,
                               _("Stream Output MRL") );
    wxStaticBoxSizer *mrl_sizer = new wxStaticBoxSizer( mrl_box,
                                                        wxHORIZONTAL );
    wxStaticText *mrl_label = new wxStaticText( panel, -1,
                                                _("Destination Target:") );
    mrl_combo = new wxComboBox( panel, MRL_Event, mrl,
                                wxPoint(20,25), wxSize(120, -1),
                                0, NULL );
    mrl_sizer->Add( mrl_label, 0, wxEXPAND | wxALL, 5 );
    mrl_sizer->Add( mrl_combo, 1, wxEXPAND | wxALL, 5 );
    mrl_sizer_sizer->Add( mrl_sizer, 1, wxEXPAND | wxALL, 5 );

    /* Create the output encapsulation panel */
    encapsulation_panel = EncapsulationPanel( panel );

    /* Create the access output panel */
    access_panel = AccessPanel( panel );

    /* Separation */
    wxStaticLine *static_line = new wxStaticLine( panel, wxID_OK );

    /* Create the buttons */
    wxButton *ok_button = new wxButton( panel, wxID_OK, _("OK") );
    ok_button->SetDefault();
    wxButton *cancel_button = new wxButton( panel, wxID_CANCEL, _("Cancel") );

    /* Place everything in sizers */
    wxBoxSizer *button_sizer = new wxBoxSizer( wxHORIZONTAL );
    button_sizer->Add( ok_button, 0, wxALL, 5 );
    button_sizer->Add( cancel_button, 0, wxALL, 5 );
    button_sizer->Layout();
    wxBoxSizer *main_sizer = new wxBoxSizer( wxVERTICAL );
    wxBoxSizer *panel_sizer = new wxBoxSizer( wxVERTICAL );
    panel_sizer->Add( mrl_sizer_sizer, 0, wxEXPAND, 5 );
    panel_sizer->Add( access_panel, 1, wxEXPAND | wxALL, 5 );
    panel_sizer->Add( encapsulation_panel, 0, wxEXPAND | wxALL, 5 );
    panel_sizer->Add( static_line, 0, wxEXPAND | wxALL, 5 );
    panel_sizer->Add( button_sizer, 0, wxALIGN_LEFT | wxALIGN_BOTTOM |
                      wxALL, 5 );
    panel_sizer->Layout();
    panel->SetSizerAndFit( panel_sizer );
    main_sizer->Add( panel, 1, wxGROW, 0 );
    main_sizer->Layout();
    SetSizerAndFit( main_sizer );

    /* Update all the values */
    ParseMRL();
}

SoutDialog::~SoutDialog()
{
}

/*****************************************************************************
 * Private methods.
 *****************************************************************************/
void SoutDialog::UpdateMRL()
{
    wxString encapsulation;

    switch( i_encapsulation_type )
    {
    case PS_ENCAPSULATION:
        encapsulation = "/ps";
        break;
    case AVI_ENCAPSULATION:
        encapsulation = "/avi";
        break;
    case OGG_ENCAPSULATION:
        encapsulation = "/ogg";
        break;
    case TS_ENCAPSULATION:
    default:
        encapsulation = "/ts";
        break;
    }

    switch( i_access_type )
    {
    case FILE_ACCESS_OUT:
        mrl = "file" + encapsulation + ":" + file_combo->GetValue();
        break;

    case HTTP_ACCESS_OUT:
        mrl = "http" + encapsulation + ":" + net_addr->GetLineText(0)
              + wxString::Format( ":%d", net_port->GetValue() );
        break;

    case UDP_ACCESS_OUT:
        mrl = "udp" + encapsulation + ":"
              + net_addr->GetLineText(0)
              + wxString::Format( ":%d", net_port->GetValue() );
        break;

    case RTP_ACCESS_OUT:
        mrl = "rtp" + encapsulation + ":"
              + net_addr->GetLineText(0)
              + wxString::Format( ":%d", net_port->GetValue() );
        break;
    }

    mrl_combo->SetValue( mrl );
}

wxPanel *SoutDialog::AccessPanel( wxWindow* parent )
{
    int i;
    wxPanel *panel = new wxPanel( parent, -1, wxDefaultPosition,
                                  wxSize(200, 200) );

    wxFlexGridSizer *sizer = new wxFlexGridSizer( 2, 4, 20 );
    wxStaticBox *panel_box = new wxStaticBox( panel, -1, _("Output Method") );
    wxStaticBoxSizer *panel_sizer = new wxStaticBoxSizer( panel_box,
                                                          wxHORIZONTAL );

    static const wxString access_output_array[] =
    {
        _("File"),
        _("HTTP"),
        _("UDP"),
        _("RTP")
    };

    for( i=0; i<4; i++ )
    {
        access_radios[i] = new wxRadioButton( panel, AccessRadio1_Event + i,
                                              access_output_array[i],
                                              wxDefaultPosition, wxDefaultSize,
                                              wxRB_SINGLE );

        access_subpanels[i] = new wxPanel( panel, -1,
                                           wxDefaultPosition, wxDefaultSize );
    }

    /* File row */
    wxFlexGridSizer *subpanel_sizer;
    wxStaticText *label;
    subpanel_sizer = new wxFlexGridSizer( 3, 1, 20 );
    label = new wxStaticText( access_subpanels[0], -1, _("Filename") );
    file_combo = new wxComboBox( access_subpanels[0], FileName_Event, "",
                                 wxPoint(20,25), wxSize(200, -1), 0, NULL );
    wxButton *browse_button = new wxButton( access_subpanels[0],
                                            FileBrowse_Event, _("Browse...") );
    subpanel_sizer->Add( label, 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL );
    subpanel_sizer->Add( file_combo, 1,
                         wxEXPAND | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL );
    subpanel_sizer->Add( browse_button, 0,
                         wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL );

    access_subpanels[0]->SetSizerAndFit( subpanel_sizer );

    /* Net row */
    subpanel_sizer = new wxFlexGridSizer( 4, 1, 20 );
    label = new wxStaticText( access_subpanels[2], -1, _("Address") );
    net_addr = new wxTextCtrl( access_subpanels[2], NetAddr_Event, "",
                               wxDefaultPosition, wxSize( 200, -1 ),
                               wxTE_PROCESS_ENTER);
    subpanel_sizer->Add( label, 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL );
    subpanel_sizer->Add( net_addr, 1,
                         wxEXPAND | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL );

    label = new wxStaticText( access_subpanels[2], -1, _("Port") );
    net_port = new wxSpinCtrl( access_subpanels[2], NetPort_Event,
                               wxString::Format(_("%d"), 0/*val*/),
                               wxDefaultPosition, wxDefaultSize,
                               wxSP_ARROW_KEYS,
                               0, 16000, 0/*val*/);

    subpanel_sizer->Add( label, 0, wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL );
    subpanel_sizer->Add( net_port, 0,
                         wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL );

    access_subpanels[2]->SetSizerAndFit( subpanel_sizer );


    /* Stuff everything into the main panel */
    for( i=0; i<4; i++ )
    {
        sizer->Add( access_radios[i], 0,
                    wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL );
        sizer->Add( access_subpanels[i], 1, wxEXPAND | wxALIGN_CENTER_VERTICAL
                    | wxALIGN_LEFT );
    }

    panel_sizer->Add( sizer, 1, wxEXPAND, 0 );

    panel->SetSizerAndFit( panel_sizer );

    return panel;
}

wxPanel *SoutDialog::EncapsulationPanel( wxWindow* parent )
{
    int i;
    wxPanel *panel = new wxPanel( parent, -1, wxDefaultPosition,
                                  wxSize(200, 200) );

    wxStaticBox *panel_box = new wxStaticBox( panel, -1,
                                              _("Encapsulation Method") );
    wxStaticBoxSizer *panel_sizer = new wxStaticBoxSizer( panel_box,
                                                          wxHORIZONTAL );

    static const wxString encapsulation_array[] =
    {
        _("MPEG TS"),
        _("MPEG PS"),
        _("AVI"),
        _("Ogg")
    };

    /* Stuff everything into the main panel */
    for( i=0; i<4; i++ )
    {
        encapsulation_radios[i] =
            new wxRadioButton( panel, EncapsulationRadio1_Event + i,
                               encapsulation_array[i] );
        panel_sizer->Add( encapsulation_radios[i], 0,
                          wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL );
    }

    panel->SetSizerAndFit( panel_sizer );

    /* Update encapsulation panel */
    encapsulation_radios[0]->Enable();
    i_encapsulation_type = TS_ENCAPSULATION;

    return panel;
}

void SoutDialog::ParseMRL()
{
    /* Initialise MRL value */
    char *psz_sout = config_GetPsz( p_intf, "sout" );
    if( psz_sout )
    {
        mrl = psz_sout;
        free( psz_sout );
    }

    /* Parse the MRL */
    wxString access = mrl.BeforeFirst( '/' );
    wxString encapsulation = mrl.BeforeFirst( ':' ).AfterFirst('/');

    if( !access.Cmp( "http" ) )
    {
        i_access_type = HTTP_ACCESS_OUT;
    }
    else if( !access.Cmp( "udp" ) )
    {
        i_access_type = UDP_ACCESS_OUT;
    }
    else if( !access.Cmp( "rtp" ) )
    {
        i_access_type = RTP_ACCESS_OUT;
    }
    else
    {
        i_access_type = FILE_ACCESS_OUT;
    }

    if( !encapsulation.Cmp( "ps" ) )
    {
        i_encapsulation_type = PS_ENCAPSULATION;
    }
    else if( !encapsulation.Cmp( "avi" ) )
    {
        i_encapsulation_type = AVI_ENCAPSULATION;
    }
    else if( !encapsulation.Cmp( "ogg" ) )
    {
        i_encapsulation_type = OGG_ENCAPSULATION;
    }
    else
    {
        i_encapsulation_type = TS_ENCAPSULATION;
    }

    wxString second_part = mrl.AfterFirst( ':' );

    if( i_access_type == FILE_ACCESS_OUT )
    {
        /* The whole second part of the MRL is the filename */
        file_combo->SetValue( second_part );
    }
    else
    {
        /* we've got address:port */
        wxString address = second_part.BeforeLast( ':' );
        net_addr->SetValue( address );

        long int i_port;
        wxString port = second_part.AfterLast( ':' );
        if( port.ToLong( &i_port ) )
        {
            net_port->SetValue( i_port );
        }
        else
        {
            net_port->SetValue( config_GetInt( p_intf, "server-port" ) );
        }
    }

    /* Update access output panel */
    wxCommandEvent dummy_event;
    dummy_event.SetId( AccessRadio1_Event + i_access_type );
    OnAccessTypeChange( dummy_event );

    /* Update encapsulation output panel */
    dummy_event.SetId( EncapsulationRadio1_Event + i_encapsulation_type );
    OnEncapsulationChange( dummy_event );
}

/*****************************************************************************
 * Events methods.
 *****************************************************************************/
void SoutDialog::OnOk( wxCommandEvent& WXUNUSED(event) )
{
    EndModal( wxID_OK );
}

void SoutDialog::OnCancel( wxCommandEvent& WXUNUSED(event) )
{
    EndModal( wxID_CANCEL );
}

void SoutDialog::OnMRLChange( wxCommandEvent& event )
{
    mrl = event.GetString();
}

/*****************************************************************************
 * Access output panel event methods.
 *****************************************************************************/
void SoutDialog::OnAccessTypeChange( wxCommandEvent& event )
{
    int i;
    i_access_type = event.GetId() - AccessRadio1_Event;

    switch( i_access_type )
    {
    case FILE_ACCESS_OUT:
        access_subpanels[0]->Enable();
        access_subpanels[2]->Disable();
        access_subpanels[3]->Disable();
        for( i = 1; i < 4; i++ )
        {
            encapsulation_radios[i]->Enable();
        }
        break;

    case HTTP_ACCESS_OUT:
        access_subpanels[0]->Disable();
        access_subpanels[2]->Enable();
        access_subpanels[3]->Disable();
        for( i = 1; i < 4; i++ )
        {
            encapsulation_radios[i]->Enable();
        }
        break;

    case UDP_ACCESS_OUT:
    case RTP_ACCESS_OUT:
        access_subpanels[0]->Disable();
        access_subpanels[2]->Enable();
        access_subpanels[3]->Enable();
        for( i = 1; i < 4; i++ )
        {
            encapsulation_radios[i]->Disable();
        }
        encapsulation_radios[TS_ENCAPSULATION]->SetValue(true);
        i_encapsulation_type = TS_ENCAPSULATION;
        break;
    }

    for( i = 0; i < 4; i++ )
    {
        access_radios[i]->SetValue( event.GetId() == (AccessRadio1_Event+i) );
    }

    UpdateMRL();
}

/*****************************************************************************
 * File access output event methods.
 *****************************************************************************/
void SoutDialog::OnFileChange( wxCommandEvent& WXUNUSED(event) )
{
    UpdateMRL();
}

void SoutDialog::OnFileBrowse( wxCommandEvent& WXUNUSED(event) )
{
    wxFileDialog dialog( this, _("Save file"), "", "", "*.*", wxSAVE );

    if( dialog.ShowModal() == wxID_OK )
    {
        file_combo->SetValue( dialog.GetPath() );
        UpdateMRL();
    }
}

/*****************************************************************************
 * Net access output event methods.
 *****************************************************************************/
void SoutDialog::OnNetChange( wxCommandEvent& WXUNUSED(event) )
{
    UpdateMRL();
}

/*****************************************************************************
 * Encapsulation panel event methods.
 *****************************************************************************/
void SoutDialog::OnEncapsulationChange( wxCommandEvent& event )
{
    i_encapsulation_type = event.GetId() - EncapsulationRadio1_Event;
    UpdateMRL();
}
