<?php

namespace App\Jobs;

use App\Jobs\Tasks\BrowseRSSLatestNewsTask;
use App\Models\RssPost;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class BrowseSingleRSSJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 20;

    protected $rss_url;

    protected $hours;

    /**
     * Create a new job instance.
     */
    public function __construct($rss_url, $hours)
    {
        $this->rss_url = $rss_url;

        $this->hours = $hours;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $raw_posts = BrowseRSSLatestNewsTask::handleSingle($this->rss_url, $this->hours);

        foreach ($raw_posts as $raw_post) {
            $rss_post = RssPost::where('post_url', $raw_post->link)->first();

            if (is_null($rss_post)) {
                $rss_post = new RssPost;
                $rss_post->post_url = $raw_post->link;
                $rss_post->post_domain = get_domain_from_url($raw_post->link);
                $rss_post->source = $raw_post->source;
                $rss_post->source_url = $raw_post->source_url;
                $rss_post->title = remove_newline($raw_post->title);
                $rss_post->slug = str_slug(remove_newline($raw_post->title));
                $rss_post->published_at = $raw_post->date;
                $rss_post->status = 'draft';

                if ($rss_post->save()) {
                    CrawlRssPostJob::dispatch($rss_post->id)->onConnection('default')->onQueue('default');
                }
            }

        }

    }
}
