#include "connor_erp_mes.h"
#include <base_utils/IFail.hxx>
#include <base_utils/TcResultStatus.hxx>

int QF_Delete_TCM(EPM_action_message_t msg) {
    ResultStatus s;
    int ifail = ITK_ok, attachment_cnt = 0;
    tag_t root_task = NULLTAG, * attachment_tags = NULL;
    char* object_string = NULL, * object_type = NULL;
    if (msg.task == NULLTAG) {
        goto end;
    }
    printf("QF_Delete_TCM\n");
    try {
        set_bypass(true);
        s = EPM_ask_root_task(msg.task, &root_task);
        s = EPM_ask_attachments(root_task, EPM_target_attachment, &attachment_cnt, &attachment_tags);
        printf("Target Count: %d\n", attachment_cnt);
        for (int i = 0; i < attachment_cnt; i++) {
            DOFREE(object_string);
            DOFREE(object_type);
            tag_t target = attachment_tags[i];
            int releaseFlag = 0;
            s = AOM_ask_value_string(target, "object_string", &object_string);
            s = WSOM_ask_object_type2(target, &object_type);
            s = EPM_ask_if_released(target, &releaseFlag);
            printf("%d. %s [%s] > %d\n", i + 1, object_string, object_type, releaseFlag);
            if (releaseFlag == 1) {
                printf(">> Remove\n");
                s = EPM_remove_attachments(root_task, 1, &target);
            }
        }
    }
    catch (const IFail& ex) {
        ifail = ex.ifail();
        cout << ex.getMessage() << endl;
        cout << "error " << ex.ifail() << endl;
    }
end:
    DOFREE(object_string);
    DOFREE(object_type);
    DOFREE(attachment_tags);
    set_bypass(false);
    printf("Finish [%d]\n", ifail);
    return ifail;
}