# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.

from trytond.i18n import gettext
from trytond.model import fields
from trytond.modules.document_incoming.exceptions import (
    DocumentIncomingProcessError)
from trytond.pool import Pool, PoolMeta
import json
import logging

logger = logging.getLogger(__name__)


class IncomingConfiguration(metaclass=PoolMeta):
    __name__ = 'document.incoming.configuration'

    default_controller = fields.Many2One('party.party', "Default Controller")


class Incoming(metaclass=PoolMeta):
    __name__ = 'document.incoming'

    created_at = fields.Function(
        fields.Date("Created At"),
        'get_created_at')
    result_notes = fields.Function(
        fields.Text("Result Notes"),
        'get_result_notes')

    @classmethod
    def __setup__(cls):
        super().__setup__()
        cls.type.selection.append(
            ('weight_report', "Weight Report"))
        cls.type.selection.append(
            ('controller', "Controller"))
        cls._order = [('create_date', 'DESC')]

    @classmethod
    def _get_results(cls):
        return super()._get_results() | {'automation.document'}

    def _process_weight_report(self):
        logger.info(
            "DOCUMENT_INCOMING_WR_START incoming=%s name=%s type=%s "
            "data_size=%s",
            getattr(self, 'id', None), getattr(self, 'name', None),
            getattr(self, 'type', None),
            len(getattr(self, 'data', None) or b""))
        WR = Pool().get('automation.document')
        wr = WR()
        wr.document = self.id
        wr.type = 'weight_report'
        wr.state = 'draft'
        WR.save([wr])
        logger.info(
            "DOCUMENT_INCOMING_WR_AUTOMATION_CREATED incoming=%s "
            "automation_document=%s",
            getattr(self, 'id', None), getattr(wr, 'id', None))
        WR.run_ocr([wr])
        WR.run_metadata([wr])
        WR.run_pipeline([wr])
        return wr
    
    def _process_controller(self):
        WR = Pool().get('automation.document')
        wr = WR()
        wr.document = self.id
        wr.type = 'controller'
        wr.state = 'draft'
        WR.save([wr])
        WR.run_ocr([wr])
        # WR.run_metadata([wr])

        return wr

    def get_created_at(self, name=None):
        create_date = getattr(self, 'create_date', None)
        if not create_date:
            return None
        return create_date.date()

    @classmethod
    def order_created_at(cls, tables):
        table, _ = tables[None]
        return [table.create_date]

    def get_result_notes(self, name=None):
        result = getattr(self, 'result', None)
        if not result:
            return ''
        if getattr(result, '__name__', None) == 'automation.document':
            return getattr(result, 'notes', '') or ''
        return ''

    # @property
    # def supplier_invoice_company(self):
    #     pass

    # @property
    # def supplier_invoice_party(self):
    #     pass
