
import os
import tempfile

from .common import slugify, file_open
from .rpc import RPCProgress


class Action(object):

    @staticmethod
    def exec_report(conn, name, data, direct_print=False, context=None):
        if context is None:
            context = {}

        data = data.copy()
        ctx = {}
        ctx.update(context)
        ctx['direct_print'] = direct_print
        args = ('report', name, 'execute', data.get('ids', []), data, ctx)
        try:
            rpc_progress = RPCProgress(conn, 'execute', args)
            res = rpc_progress.run()
        except:
            return False
        if not res:
            return False

        (type, content, print_p, name) = res

        dtemp = tempfile.mkdtemp(prefix='tryton_')

        fp_name = os.path.join(dtemp,
            slugify(name) + os.extsep + slugify(type))

        print(dtemp)
        if os.name == 'nt':
            operation = 'open'
            os.startfile(fp_name, operation)
        else:
            with open(fp_name, 'wb') as file_d:
                file_d.write(content.data)

            file_open(fp_name, type, direct_print=direct_print)
        return True
