<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 05.01.2024
 * Time: 10:29 PM
 */

namespace IMATHUZH\Qfq\External;

require_once(__DIR__ . '/../../vendor/autoload.php');

use IMATHUZH\Qfq\Core\Helper\Support;

define('QFQ_EXTERNAL', 'External call');

global $argv;


try {
    try {
        // If we are called via CLI, this typically means we're should run as a daemon.
        // Else we expect some output on the webpage or do debugging.
        $mode = Support::is_cli() ? ES_MODE_SYNC_POLL : ES_MODE_SYNC;

        switch($argv[1]??''){
            case '-s':
                $mode = ES_MODE_SYNC;
                break;
            case '-S':
                $mode = ES_MODE_SYNC_POLL;
                break;
            case '-l':
                // List folder
                $mode = ES_MODE_LIST_ALL_FOLDER;
                break;
            case '-L':
                // List folder and mail
                $mode = ES_MODE_LIST_ALL_FOLDER_ALL_MAIL;
                break;
            default:
                break;
        }

        $emailSync = new EmailSync($mode);
        $emailSync->process();

    } catch (\UserFormException $e) {
        $answer[API_MESSAGE] = $e->formatMessage();
    } catch (\CodeException $e) {
        $answer[API_MESSAGE] = $e->formatMessage();
    } catch (\DbException $e) {
        $answer[API_MESSAGE] = $e->formatMessage();
    }
} catch (\Throwable $e) {
    $answer[API_MESSAGE] = "Generic Exception: " . $e->getMessage();
}

if (!empty($answer[API_MESSAGE])) {
    echo $answer[API_MESSAGE];
}
