# Copyright (C) 2017 The Meme Factory, Inc.  http://www.meme.com/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Karl O. Pinc <kop@meme.com>

'''
Print output and manage related state.
'''

from __future__ import print_function

import sys

from . import header


#
# Constants
#

# These could be configurable, but aren't.
BREAK = '-' * header.BREAK_WIDTH  # Section break mark on report


#
# Classes
#
class Printer(object):
    def __init__(self, stock_parens=set([])):
        super(Printer, self).__init__()
        self.stock_parens = stock_parens
        self.count = 0
        self.report_items = []

    def _not_stock_paren(self, item):
        return item not in self.stock_parens

    def add_report_items(self, direntry, report_items):
        filtered = list(filter(self._not_stock_paren, report_items))
        if filtered:
            path = to_sys_encoding(direntry.path)
            for item in filtered:
                self.report_items.append((path, to_sys_encoding(item)))

    def print_section(self, text):
        if self.count == 0:
            print_break()
            self.nothing_printed = False
        self.count += 1
        print_count(self.count)
        print(to_sys_encoding(text))
        print_break()

    def print_report_items(self):
        for item in self.report_items:
            print('{0}\t{1}'.format(item[0], item[1]))


#
# Functions
#
def print_break():
    print(BREAK)


def print_count(count):
    print('Item# {0}'.format(count))


ENCODING = sys.stdout.encoding
if ENCODING is not None:
    def to_sys_encoding(text):
        return text.encode(ENCODING, 'replace').decode(ENCODING)
else:
    def to_sys_encoding(text):
        return text
