<?php

namespace App\Controllers;


use App\Models\JobModel;
class Jobs extends BaseController
{
    const STATUS_DONE = 'done';
    const STATUS_QUEUED = 'queued';
    const STATUS_RUNNING = 'running';
    const STATUS_FAILED = 'failed';

    protected $job_payload = [];
    protected $myLogger;
    /**
     * Constructs the class
     */
    // public function __construct(array $payload = ['job_name' => 'check','payload' => ['a' => 10]])
    public  function __construct()
    {
        // $this->job_payload = $payload;
        // $this->myLogger = \Config\Services::mylogger();
    }

    /**
     * add jobs to queue
     */
    public static function addJob(array $payload)
    {
        $jobModel = new JobModel();
        $myLogger = \Config\Services::mylogger();

        try
        {
            if(!is_array($payload))
            {
                throw new \InvalidArgumentException('Invalid payload format while add job');
            }

            if(!isset($payload['job_name']))
            {
                throw new \InvalidArgumentException('Job name not found while add job');
            }

            if(!isset($payload['payload']))
            {
                throw new \InvalidArgumentException('Job payload not found while add job');
            }

           $uuid = generate_uuid();
           $jobid =  $jobModel->insert(['name' => $payload['job_name'],'uuid' => $uuid,'payload' => json_encode($payload['payload']), 'status' => isset($payload['status']) ? $payload['status'] : 'queued']);
           // echo $jobid;
           log_message('error','new job {jobid} added to queue',['jobid' => $jobid]);
           return ['id' => $jobid,'uuid' => $uuid,'job_name' => $payload['job_name']];
        }
        catch(\Exception $e)
        {
            $message = $e->getMessage();
            return $message;
            log_message('error','{messgae}',['messgae' => $message]);
        }
    }

}
