#!/usr/bin/env ruby
#
# amaroK-Script for integrating soundKonverter into amaroK
#
# (c) 2005 Daniel Faust <daniel@kaligames.de>
# License: GNU General Public License V2


# FIXME after adding some files to soundkonverter, it is impossible to repeat that, until soundkonverter gets closed.

# FIXME don't open files on every request. load options on startup and save on exit!

#`dcop amarok playlist addMedia KURL`
#`dcop amarok playlist addMediaList KURL::List`
#`dcop amarok collection scanCollectionChanges`


require "uri"

begin
    require "Qt"
rescue LoadError
    error = 'Qt Ruby bindings are required for this script.'
    `dcop amarok playlist popupMessage "soundKonverter: #{error}"`
    exit
end

class MainWidget < Qt::Dialog

slots 'accept()'

def initialize(parent = nil, name = nil)
    super

    box = Qt::VBoxLayout.new( self, 11, 6 );

    lTitle = Qt::Label.new('soundKonverter plugin settings', self)
    box.addWidget( lTitle )
    lTitle.setAlignment(Qt::AlignCenter)
    font = Qt::Font.new()
    font.setPixelSize(18)
    font.setBold(true)
    lTitle.setFont(font)

    box.addSpacing( 5 )

    mediaDeviceBox = Qt::GroupBox.new( 1, Qt::Vertical, "Options for transfering to media devices", self )
    box.addWidget( mediaDeviceBox )
    mediaDeviceBox.layout().setSpacing( 6 )
    mediaDeviceBox.layout().setMargin( 6 )
    Qt::Label.new('Profile for lossy conversion:', mediaDeviceBox)
    @cTranscodeProfile = Qt::ComboBox.new(mediaDeviceBox)
    @cTranscodeProfile.insertItem("Very low")
    @cTranscodeProfile.insertItem("Low")
    @cTranscodeProfile.insertItem("Medium")
    @cTranscodeProfile.insertItem("High")
    @cTranscodeProfile.insertItem("Very high")
    @cTranscodeProfile.setCurrentItem( 1 )

#     box.addSpacing( 5 )
# 
#     rippingBox = Qt::GroupBox.new( 2, Qt::Horizontal, "Use pre-defined options for CD ripping", self )
#     box.addWidget( rippingBox )
#     rippingBox.layout().setSpacing( 6 )
#     rippingBox.layout().setMargin( 6 )
#     rippingBox.setCheckable( true )
#     rippingBox.setEnabled( false )
# 
#     profileBox = Qt::HBoxLayout.new( rippingBox, 6 );
#     lRippingProfile = Qt::Label.new('Profile:', rippingBox)
#     profileBox.addWidget( lRippingProfile )
#     @cRippingProfile = Qt::ComboBox.new(rippingBox)
#     profileBox.addWidget( @cRippingProfile )
#     @cRippingProfile.insertItem("Very low")
#     @cRippingProfile.insertItem("Low")
#     @cRippingProfile.insertItem("Medium")
#     @cRippingProfile.insertItem("High")
#     @cRippingProfile.insertItem("Very high")
#     @cRippingProfile.insertItem("Lossless")
#     @cRippingProfile.insertItem("Last used")
#     @cRippingProfile.setCurrentItem(3)
#     lRippingFormat = Qt::Label.new('Format:', rippingBox)
#     profileBox.addWidget( lRippingFormat )
#     @cRippingFormat = Qt::ComboBox.new(rippingBox)
#     profileBox.addWidget( @cRippingFormat )
#     @cRippingFormat.insertItem("ogg")
#     @cRippingFormat.insertItem("mp3")
#     @cRippingFormat.insertItem("flac")
#     directoryBox = Qt::HBoxLayout.new( rippingBox, 6 );
#     lRippingDirectory = Qt::Label.new('Directory:', rippingBox)
#     directoryBox.addWidget( lRippingDirectory )
#     @cRippingDirectory = Qt::ComboBox.new(rippingBox)
#     directoryBox.addWidget( @cRippingDirectory )
#     @cRippingDirectory.setEditable(true)
#     @cRippingDirectory.insertItem("/home/daniel/soundKonverter/%b/%d - %n - %t")
#     @cRippingDirectory.insertItem("Last used")

    box.addSpacing( 5 )

    buttonsBox = Qt::HBoxLayout.new(box)
    buttonsBox.setSpacing(6)
    buttonsBox.addStretch()
    okPushButton = Qt::PushButton.new( self, "ok" )
    buttonsBox.addWidget( okPushButton )
    okPushButton.setText( "OK" )
    okPushButton.setDefault( true )

    connect( okPushButton, SIGNAL( 'clicked()' ),
             self, SLOT( 'accept()' )
           )

    cancelPushButton = Qt::PushButton.new( self, "cancel" )
    buttonsBox.addWidget( cancelPushButton )
    cancelPushButton.setText( "Cancel" )
    cancelPushButton.setAccel( Qt::KeySequence.new(Key_Escape) )

    connect( cancelPushButton, SIGNAL( 'clicked()' ),
             self, SLOT( 'reject()' )
           )

    file = Qt::File.new( File.dirname( File.expand_path( __FILE__ ) ) + "/config" )
    if file.open( Qt::IO_ReadOnly )
        ts = Qt::TextStream.new( file )
        content = ''
        ts >> content
        if content == 'Very_low'
            @cTranscodeProfile.setCurrentItem( 0 )
        elsif content == 'Low'
            @cTranscodeProfile.setCurrentItem( 1 )
        elsif content == 'Medium'
            @cTranscodeProfile.setCurrentItem( 2 )
        elsif content == 'High'
            @cTranscodeProfile.setCurrentItem( 3 )
        elsif content == 'Very_high'
            @cTranscodeProfile.setCurrentItem( 4 )
        end
        file.close()
    end

#     file = Qt::File.new( File.dirname( File.expand_path( __FILE__ ) ) + "/profiles" )
#     if file.open( Qt::IO_ReadOnly )
#         ts = Qt::TextStream.new( file )
#         while !ts.eof()
#             content = ''
#             ts >> content
#             @cProfile.insertItem( content )
#             ts >> content
#         end
# 
#         file.close()
#     end
end


def accept()
    file = Qt::File.new( File.dirname( File.expand_path( __FILE__ ) ) + "/config" )
    if file.open( Qt::IO_WriteOnly )
        ts = Qt::TextStream.new( file )
        if @cTranscodeProfile.currentText() == 'Very low'
            content = 'Very_low'
        elsif @cTranscodeProfile.currentText() == 'Low'
            content = 'Low'
        elsif @cTranscodeProfile.currentText() == 'Medium'
            content = 'Medium'
        elsif @cTranscodeProfile.currentText() == 'High'
            content = 'High'
        elsif @cTranscodeProfile.currentText() == 'Very high'
            content = 'Very_high'
        end
        ts << content + "\n"
        file.close()
    end

    super
end

end


MenuItemName1 = "soundKonverter \"Convert selected files\""
MenuItemName2 = "soundKonverter \"Add Replay Gain to selected files\""
MenuItemName3 = "soundKonverter \"Rip and play audio CD\""


def cleanup()
    `dcop amarok script removeCustomMenuItem #{MenuItemName1}`
    `dcop amarok script removeCustomMenuItem #{MenuItemName2}`
    `dcop amarok script removeCustomMenuItem #{MenuItemName3}`
end


trap( "SIGTERM" ) { cleanup() }

`dcop amarok script addCustomMenuItem #{MenuItemName1}`
`dcop amarok script addCustomMenuItem #{MenuItemName2}`
`dcop amarok script addCustomMenuItem #{MenuItemName3}`

loop do
    message = gets().chomp()
    command = /[A-Za-z]*/.match( message ).to_s()

    case command
        when "configure"
            app = Qt::Application.new(ARGV)
            widget = MainWidget.new
            app.setMainWidget(widget)
            widget.show()
            app.exec()

        when "transcode"
            args = message.split()
            filename = args[1]
            #uri = URI.parse( args[1] )
            #filename = URI.unescape( uri.path() )
            filetype = args[2]
            profile = ''

            file = Qt::File.new( File.dirname( File.expand_path( __FILE__ ) ) + "/formats" )
            if file.open( Qt::IO_ReadOnly )
                ts = Qt::TextStream.new( file )
                while !ts.eof()
                    mode = ''
                    formats = ''
                    ts >> mode
                    ts >> formats
                    if formats.split(',').include?( filetype )
                        profile = mode
                    end
                end
                file.close()
            end

            if profile == ''
                file = Qt::File.new( File.dirname( File.expand_path( __FILE__ ) ) + "/config" )
                if file.open( Qt::IO_ReadOnly )
                    ts = Qt::TextStream.new( file )
                    content = ''
                    ts >> content
                    if content == 'Very_low'
                        profile = 'Very low'
                elsif content == 'Low'
                        profile = 'Low'
                elsif content == 'Medium'
                        profile = 'Medium'
                elsif content == 'High'
                        profile = 'High'
                elsif content == 'Very_high'
                        profile = 'Very high'
                    end
                    file.close()
              else
                    profile = 'Low'
                end
            end

            `dcop amarok playlist shortStatusMessage "starting soundKonverter in background"`
            `soundkonverter --invisible --profile '#{profile}' --format '#{filetype}' --output '/tmp' --command "dcop amarok mediabrowser transcodingFinished %u file://%o" '#{filename}'`

        when "customMenuClicked"
            if message.include?( "Convert selected files" )
                args = message.split()
                # Remove the command args
                5.times() { args.delete_at( 0 ) }

                # Iterate over all selected files
                files = ''
                args.each() do |arg|
                    uri = URI.parse( arg )
                    file = URI.unescape( uri.path() )
                    files += ' "'+file+'"'
                end
                `dcop amarok playlist shortStatusMessage "starting soundKonverter"`
                `soundkonverter #{files}`
            end
            if message.include?( "Add Replay Gain to selected files" )
                args = message.split()
                # Remove the command args
                8.times() { args.delete_at( 0 ) }

                files = ''
                args.each() do |arg|
                    uri = URI.parse( arg )
                    file = URI.unescape( uri.path() )
                    files += ' "'+file+'"'
                end
                `dcop amarok playlist shortStatusMessage "starting soundKonverter"`
                `soundkonverter --replaygain #{files}`
            end
            if message.include?( "Rip and play audio CD" )
                `dcop amarok playlist popupMessage "Select all tracks to rip and press 'Start' in order to start ripping.\nThe tracks will be added to the playlist, when they are ready."`
                #`dcop amarok playlist shortStatusMessage "starting soundKonverter"`
                `soundkonverter --invisible --rip auto --command "dcop amarok playlist addMedia %o"`
            end
    end
end

