# -*- coding: utf-8 -*-
from ppms import ppms
from ppms.constants import *
from ppms.interface import MtsModule, modify_record_and_save_if_necessary

def get_load_records_from_mts_record(mts_record):
    for task_record in mts_record.get_children('task_source_records'):
        for res_record in task_record.get_children('res_source_records'):
            for load_record in res_record.get_children('load_act_source_records'):
                # Use the dtp_record so we don't have to rely on Mts customizing
                dtp_record = load_record.get_dtp_record()

                di_pr_id = dtp_record.get_di('pr_id')
                di_item = dtp_record.get_di('item')

                if di_item is None:
                    raise ValueError('Record does not have the attribute "item" which is necessary for stamping!')

                if di_pr_id is None:
                    raise ValueError('Record does not have the attribute "pr_id" which is necessary for stamping!')

                project_id = di_pr_id.get_value()
                position = di_item.get_value()
                    
                stamp_fields_in_472(project_id=project_id, position=position)
    return


def stamp_fields_in_472(project_id, position):
    """Stamp the export fields in DT472"""
    # TODO: Change the fields to stamp here!
    load_record = ppms.search_record(472, [project_id, position], ['L100_exported_on', 'L100_exported_by'])
    
    if load_record is None:
        raise ValueError('No load record with project {} and position {}'.format(project_id, position))
    
    update_attributes = {'L100_exported_on': ppms.uvar_get(SYS_VAR_TODAY),
                         'L100_exported_by': ppms.uvar_get(SYS_VAR_LOGGED_IN_USER)}

    return modify_record_and_save_if_necessary(record=load_record, update_attributes=update_attributes)


class MtsNorrdLoadModule(MtsModule):
    """Subclass for exporting load records with stamping"""

    def fetch_value(self, mts_record, python_id):
        """Remember the currently processed mts record for stamping"""
        self.mts_record = mts_record

        return super().fetch_value(mts_record=mts_record, python_id=python_id)

    def send(self):
        """Yield a load record and stamp it when it was transferred successfully"""
        for record_dictionary in MtsModule.send(self):
            return_value = yield record_dictionary

            if return_value is True:
               get_load_records_from_mts_record(mts_record=self.mts_record)


            super().send()