__all__ = ['output']

import collections
from io import BytesIO, BufferedReader
import json
import sys

from ..require import require

def output(result, fn=None, raw=False):
    if getattr(fn, 'no_result', False): return
    if _isiterator(result):
        for a in result:
            output(a, fn, raw)
    elif isinstance(result, bytes):
        sys.stdout.buffer.write(result)
    elif hasattr(result, 'getpixel'):
        # assume result is an instance of PIL.Image
        buffer = BytesIO()
        result.save(buffer, format='JPEG')
        sys.stdout.buffer.write(buffer.getvalue())
    elif isinstance(result, (str, bytes)) and (raw or getattr(fn, 'raw_output', False)):
        sys.stdout.write(result)
    else:
        # print(to_json(result), flush=True)
        print(
            json.dumps(result, separators=(',', ':')),
            flush=True
        )

def _isiterator(a):
    return isinstance(a, collections.abc.Iterable) and not isinstance(a, (str, bytes, list, dict, tuple, BufferedReader))
