package GCImport::GCImportFolder;

###################################################
#
#  Copyright 2005-2007 Tian
#
#  This file is part of GCstar.
#
#  GCstar 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.
#
#  GCstar 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 GCstar; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
###################################################

use strict;

use GCImport::GCImportBase;

{
    package GCImport::GCImporterFolder;

    use File::Find;
    use File::Basename;
    use base qw(GCImport::GCImportBaseClass);

    use GCPlugins;

    sub new
    {
        my $proto = shift;
        my $class = ref($proto) || $proto;
        my $self  = $class->SUPER::new();
        
        bless ($self, $class);
        return $self;
    }

    sub wantsFieldsSelection
    {
        return 0;
    }

    sub wantsFileSelection
    {
        return 1;
    }
    
    sub wantsDirectorySelection
    {
        return 1;
    }
    
    sub getFilePatterns
    {
       return ();
    }
    
    #Return supported models name
    sub getModels
    {
        return ['GCfilms', 'GCMusics'];
    }

    sub getOptions
    {
        my $self = shift;
        
        my $pluginsList = '';
        foreach (@{$self->{model}->getPluginsNames})
        {
            my $plugin = $GCPlugins::pluginsMap{$self->{model}->getName}->{$_};
            $pluginsList .= $plugin->getName . ',';
        }
        
        
        return [
            {
                name => 'plugin',
                type => 'options',
                label => 'Plugin',
                valuesList => $pluginsList
            },

            {
                name => 'first',
                type => 'yesno',
                label => 'UseFirst',
                default => '1'
            },

            {
                name => 'recursive',
                type => 'yesno',
                label => 'Recursive',
                default => '1'
            },

            {
                name => 'suffixes',
                type => 'short text',
                label => 'Suffixes',
                tooltip => 'SuffixesTooltip',
                default => '',
            },

            {
                name => 'remove',
                type => 'short text',
                label => 'Remove',
                tooltip => 'RemoveTooltip',
                default => '',
            },
        ];
        
        
    }
      
    sub getModelName
    {
        my $self = shift;
        return $self->{model}->getName;
    }

    # Required by extracter to make this class acts as a panel
    sub AUTOLOAD
    {
        return [];
    }

    sub getItemsArray
    {
        my ($self, $directory) = @_;
        my @result;
        my @filesList;

        #First we try to get the correct plugin
        my $plugin = $GCPlugins::pluginsMap{$self->{model}->getName}->{$self->{options}->{plugin}};
        my $titleField = $self->{model}->{commonFields}->{title};
        my $fileField = $self->{model}->{commonFields}->{play};

        # Required by extracter
        $self->{lang} = $self->{options}->{lang};

        (my $suffixes = $self->{options}->{suffixes}) =~ s/,;/\|/g;
        $suffixes =~ s/\*\.//g;
        # Create list of files
        if ($self->{options}->{recursive})
        {
            find(sub {
                return if -d $File::Find::name;
                return if ! /$suffixes$/;
                push @filesList, $File::Find::name;
            }, $directory);
        }
        else
        {
            foreach (glob "$directory/*")
            {
                next if -d $_;
                next if ! /$suffixes$/;
                push @filesList, $_;
            }
        }
        my $resultsDialog;
        if (!$self->{options}->{first})
        {
            $resultsDialog = $self->{options}->{parent}->getDialog('Results');
            $resultsDialog->setModel($self->{model}, $self->{model}->{fieldsInfo});
            $resultsDialog->setMultipleSelection(0);
        }

        (my $removed = $self->{options}->{remove}) =~ s/[,; ]/\|/g;
        foreach my $file(@filesList)
        {
            my $extracter = $self->{model}->getExtracter($self, $file, $self, $self->{model});
            my $extracted = $extracter->getInfo;

            my $name = basename($file);
            # Filter the name
            # Remove suffix
            $name =~ s/\.[^.]*$//;
            # Remove everything between () {} []
            $name =~ s/[\(\[\{].*?[\)\]\}]//g;
            # Remove special characters
            $name =~ s/[-\._,#@"']/ /g;
            #'"
            # Remove info from extracter for movies
            if ($self->{model}->getName eq 'GCfilms')
            {
                my $info = $extracted->{video}->{value}.'|'.$extracted->{audio}->{value}->[0]->[1];
                $info =~ s/ (.*?)//g;
                $name =~ s/$info//g;
            }
            $name =~ s/$removed//gi;

            # $name contains the title to search
            $plugin->{title} = $name;
            $plugin->{type} = 'load';
            $plugin->{urlField} = $self->{model}->{commonFields}->{url};

            #Initialize what will be pushed in the array
            my $info = {$titleField => $name};
        
            $self->{options}->{parent}->setWaitCursor($self->{options}->{lang}->{StatusSearch}.' ('.$name.')');
            $plugin->load;

            my $itemNumber = $plugin->getItemsNumber;

            if ($itemNumber != 0)
            {
                $plugin->{type} = 'info';
                if (($itemNumber == 1) || ($self->{options}->{first}))
                {
                    $plugin->{wantedIdx} = 0;
                }
                else
                {
                    my $withNext = 0;
                    my @items = $plugin->getItems;
                    $resultsDialog->setWithNext(0);
                    $resultsDialog->setSearchPlugin($plugin);
                    $resultsDialog->setList($name, @items);
                    $resultsDialog->show;
                    if ($resultsDialog->{validated})
                    {
                        $plugin->{wantedIdx} = $resultsDialog->getItemsIndexes->[0];
                    }
                }
                $info = $plugin->getItemInfo;
                my $title = $info->{$titleField};
                $self->{options}->{parent}->{defaultPictureSuffix} = $plugin->getDefaultPictureSuffix;
                foreach my $field(@{$self->{model}->{managedImages}})
                {
                    $info->{$field} = '' if $info->{$field} eq 'empty';
                    next if !$info->{$field};
                    ($info->{$field}) = $self->{options}->{parent}->downloadPicture($info->{$field}, $title);
                }
                $info->{comment} = $self->getLang->{CommentAuto}
                                 . "\n"
                                 . $self->getLang->{CommentSite}
                                 . $plugin->getName()
                                 . "\n"
                                 . $self->getLang->{CommentTitle}
                                 . $name
                                 . "\n"
                                 . $extracted->{comment}->{displayed};

                
           }
            
            # Add the default value
            my $defaultInfo = $self->{model}->getInitInfo;
            foreach my $field(keys %$defaultInfo)
            {
                next if exists $info->{$field};
                $info->{$field} = $defaultInfo->{$field};
            }

                # Addd info from file
            $info->{$fileField} = $file;
            foreach my $field(keys %$extracted)
            {
                next if $field eq 'comment';
                $info->{$field} = $extracted->{$field}->{value};
            }

            push @result, $info;
            $self->{options}->{parent}->restoreCursor;            
        }
        return \@result;
    }
    
    
    sub getEndInfo
    {
        my $self = shift;
        my $message;
                
        return $message;
    }
}

1;
