# -*- coding: UTF-8 -*-

# Copyright (C) 2015-2016 Avencall
#
# 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 3 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.


import logging

from xivo_dao.helpers import errors as dao_errors
from xivo_dao.helpers.exception import ServiceError

logger = logging.getLogger(__name__)


class ImportService(object):

    def __init__(self, entry_creator, entry_associator, entry_updater):
        self.entry_creator = entry_creator
        self.entry_associator = entry_associator
        self.entry_updater = entry_updater

    def import_rows(self, parser):
        created = []
        errors = []
        warnings = []

        logger.info("Import from CSV started")
        for row in parser:
            try:
                logger.debug("Import from CSV: importing row %s", row.position)
                entry = self.create_entry(row)
                created.append(entry)

                self.add_warnings(row, warnings)

            except ServiceError as e:
                logger.warn("Import from CSV: ERROR importing CSV row %s: %s", row.position, e)
                errors.append(row.format_error(e))
        logger.info("Import from CSV finished")

        return created, errors, warnings

    def create_entry(self, row):
        entry = self.entry_creator.create(row)
        self.entry_associator.associate(entry)
        return entry

    def update_rows(self, parser):
        updated = []
        errors = []
        warnings = []

        logger.info("Update from CSV started")
        for row in parser:
            try:
                logger.debug("Update from CSV: importing row %s", row.position)
                entry = self.update_row(row)
                updated.append(entry)

                self.add_warnings(row, warnings)

            except ServiceError as e:
                logger.warn("Update from CSV: ERROR importing CSV row %s: %s", row.position, e)
                errors.append(row.format_error(e))
        logger.info("Update from CSV finished")

        return updated, errors, warnings

    def update_row(self, row):
        entry = self.entry_updater.update_row(row)
        return entry

    def add_warnings(self, row, warnings):
        warnings_flat = [item for sublist in row.get_warnings() for item in sublist]
        if warnings_flat:
            warning_message = dao_errors.csv_import_password_policy(warnings_flat, "Password policy warning")
            warning = row.format_error(warning_message)
            logger.warn("Import from CSV: WARN importing CSV row %s: %s", row.position, warning['message'])
            warnings.append(warning)
