package Stanford::Schema::WebApps::SharedEmail;

use strict;
use warnings FATAL => 'all';

use base qw(DBIx::Class::Schema);

use Carp;

# connect: Override the default schema connection subroutine.
# We take a single hashref, and use the following keys:
#     shared_email_db_host: The hostname to connect to
#     shared_email_db_name: The database name
#     shared_email_db_port: An optional database server port
#     shared_email_db_passwd_file: The file containing the password
# When connecting, we make sure to tell DBI to enable AutoCommit (which is
# what DBIx::Class prefers), and we tell DBD that all tables are utf8.
sub connect { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
    my ($class, $config) = @_;

    # Build our DSN
    my $dsn = 'DBI:mysql';

    croak('Missing shared_email_db_host')
        unless exists($config->{'shared_email_db_host'});
    $dsn .= ':host=' . $config->{'shared_email_db_host'};

    croak('Missing shared_email_db_name')
        unless exists($config->{'shared_email_db_name'});
    $dsn .= ':database=' . $config->{'shared_email_db_name'};

    if (exists($config->{'shared_email_db_port'})) {
        $dsn .= ':port=' . $config->{'shared_email_db_port'};
    }

    # Read in the password
    if (!exists($config->{'shared_email_db_passwd_file'})) {
        croak('Missing shared_email_db_passwd_file');
    }
    my $password;
    open my $passfh, '<', $config->{'shared_email_db_passwd_file'}
    or croak("Error reading shared_email_db_passwd_file: $!");
    $password = <$passfh>;
    chomp $password;
    close $passfh;

    # Actually make the connection
    return $class->SUPER::connect($dsn, $config->{'shared_email_db_user'},
           $password, {
        mysql_enable_utf8 => 1,
        AutoCommit => 1,
    });
}

# sqlt_deploy_hook: Modify schema deployment to set table type and charset
# DBIx::Class defaults to using the MySQL-default storage engine and
# character set, but we want to be sure about what we're using.
# This solution came from the following web page:
# http://lists.scsys.co.uk/pipermail/dbix-class/2008-June/006353.html
sub sqlt_deploy_hook {
    my ($self, $sqlt_schema) = @_;

    for my $table ($sqlt_schema->get_tables) {
        $table->extra(
            mysql_table_type => 'InnoDB',
            mysql_charset    => 'utf8',
        );
    }

    return;
}

__PACKAGE__->load_namespaces();

1;
