# -*- coding: UTF-8 -*-
#
# Copyright (C) 2007 by Jan Dittberner.
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.
#
# Version: $Id$

import ConfigParser, os
from subprocess import *
from sqlalchemy import *
from gnuviechadmin.exceptions import *

class BackendEntity(object):
    """This is the abstract base class for all backend entity classes."""

    def __init__(self, verbose = False):
        self.verbose = verbose
        self.config = ConfigParser.ConfigParser()
        self.config.readfp(open('gnuviechadmin/defaults.cfg'))
        self.config.read(['gnuviechadmin/gva.cfg',
                          os.path.expanduser('~/.gva.cfg')])

    def __repr__(self):
        if self.verbose:
            cols = [col for col in \
                    object_mapper(self).local_table.columns.keys()]
            format = "%(class)s:"
            format = format + ", ".join([col + "=%(" + col + ")s" for col in \
                                         cols])
            data = {'class' : self.__class__.__name__}
        else:
            cols = self._shortkeys
            format = ",".join("%(" + col + ")s" for col in cols)
            data = {}
        data.update(dict([(col, self.__getattribute__(col)) for col in cols]))
        return format % data

    def sucommand(self, cmdline, pipedata = None):
        """Executes a command as root using the configured suwrapper
        command. If a pipe is specified it is used as stdin of the
        subprocess."""
        suwrapper = self.config.get('common', 'suwrapper')
        toexec = "%s %s" % (suwrapper, cmdline)
        if pipedata:
            p = Popen(toexec, shell = True, stdin=PIPE)
            pipe = p.stdin
            print >>pipe, pipedata
            pipe.close()
            sts = os.waitpid(p.pid, 0)
            if self.verbose:
                print "%s|%s: %d" % (pipedata, toexec, sts[1])
        else:
            p = Popen(toexec, shell = True)
            sts = os.waitpid(p.pid, 0)
            if self.verbose:
                print "%s: %s" % (toexec, sts[1])
        return sts[1]

    def validate(self):
        """Validates whether all mandatory fields of the entity have
        values."""
        missingfields = []
        for key in [col.name for col in \
                    object_mapper(self).local_table.columns \
                    if not col.primary_key and not col.nullable]:
            if self.__getattribute__(key) is None:
                missingfields.append(key)
        if missingfields:
            raise MissingFieldsError(missingfields)