package GCImport::GCImportCSV;

###################################################
#
#  Copyright 2005 Tian
#
#  This file is part of GCfilms.
#
#  GCfilms 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.
#
#  GCfilms 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 GCfilms; 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::GCImporterCSV;

    use base qw(GCImport::GCImportBaseClass);

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

    sub wantsFieldsSelection
    {
        return 1;
    }

    sub wantsFileSelection
    {
        return 1;
    }
    
    sub getName
    {
        my $self = shift;
        
        return "CSV";
    }
    
    sub getFilePatterns
    {
       return (['CSV (*.csv)', '*.csv']);
    }
    
    sub getOptions
    {
        my $self = shift;
        
        return [
            {
                name => 'withHeader',
                type => 'checkBox',
                label => 'ImportCSVHeader',
                default => '1'
            },

            {
                name => 'sep',
                type => 'shortText',
                label => 'ExportCSVSeparator',
                default => ';'
            },
        ];
        
        
    }
      
    sub getMoviesArray
    {
        my ($self, $file) = @_;
        my @result;

        open MOVIES, $file;
        binmode(MOVIES, ':utf8');

        my $i = 0;
        my $sep = $self->{options}->{sep};
        my $ignoreFirstLine = $self->{options}->{withHeader};

        while (<MOVIES>)
        {
            if ($ignoreFirstLine)
            {
                $ignoreFirstLine = 0;
                next;
            }
        
            chomp;
            # Special characters are escaped
            my @values =  split m/\Q$sep\E/;

            $result[$i] = {};
            my $j = 0;
            foreach (@{$self->{options}->{fields}})
            {
                $result[$i]->{$_} = $values[$j];
                $j++;
            }
	    
            $i++;
        }
        close MOVIES;


        return \@result;
    }
    
    
    sub getEndInfo
    {
        my $self = shift;
        my $message;
                
        return $message;
    }
}

1;