#!/usr/bin/perl

###########################
### Autor: Sebastian Enger / B.Sc. 
### Copyright: Sebastian Enger
### Licence: Commercial
### Version: 1.1.1  - 2013-09-18
### Contact: sebastian.enger@gmail.com
###########################

package Crawler::DB;
# 
use strict;
use Crawler::Config;

use DBI;

# Konstruktor
sub new {
	
	my ($class) 	= @_;
	
	my $config 		= Crawler::Config->new();
	my $isRead 		= $config->read("Database");
	
	my $database 	= $isRead->{database};
	my $user 		= $isRead->{user};
	my $password 	= $isRead->{password};
	my $host 		= $isRead->{host};
	my $table 		= $isRead->{table};
	
	my $dbh = DBI->connect("dbi:mysql:dbname=$database",$user,$password, {
		AutoCommit => 1,#0=$dbh->commit(); 
		RaiseError => 1,
	  });
  
	my $self = {
		'dbh' => $dbh,
		'config' => $config,
		'db_table' => $table,
	};
	# connect to database on class initialization
	# Create table $today_trends (2013-09-27_trends) bei jedem start neu
	
	bless $self, $class;
  return $self;
}


sub save(){

	my $self 		= shift;
	
	my @googlelinks = $self->{db_flat}->{googlelinks};
	my @binglinks 	= $self->{db_flat}->{binglinks};
	my $content		= $self->{db_flat}->{content};
	my $cloud		= $self->{db_flat}->{rawcloud};
	my $source		= $self->{db_flat}->{source};
	my @twitter		= $self->{db_flat}->{twitterlinks};
	
	my $tablename 	= $self->{db_table};
	my $timestamp 	= time();
	
	my $googlelinks = join("\n", @googlelinks);
	my $binglinks 	= join("\n", @binglinks);
	my $twitterlinks= join("\n", @twitter);
	
	my $query = sprintf("%s (%s, %s, %s, %s, %s, %s)",
		"INSERT INTO $tablename (content,tagcloud,googlelinks,binglinks,twitterlinks,source,timestamp,id) VALUES",
		$dbh->quote( $content ),
		$dbh->quote( $cloud ),
		$dbh->quote( $googlelinks ),
		$dbh->quote( $binglinks ),
		$dbh->quote( $twitterlinks ),
		$dbh->quote( $source ),
		$dbh->quote( $timestamp ),
		$dbh->quote("")
	);
	
	eval { $self->{dbh}->do($query) };
	warn "Crawler::DB->save() -> Error While Saving to Database\n" if $@; 

### LATER: comment out	$self->{db_flat}->empty();
	return 1;
}