<?php

namespace App\Parser;

use Absmoca\Leboncoin;
use App\ParsedHome;
use App\Parser;

class LBC extends Parser
{
    public function __construct($url)
    {
        parent::__construct($url);
    }

    /**
     * @return \App\ParsedHome
     */
    public function parse(): ParsedHome
    {
        $idAnnonce = (int) $this->getIdAnnonceFromUrl($this->url);
        $lbc = new Leboncoin();
        $annonce = $lbc->getAnnonce($idAnnonce);
        $parsedHome = new ParsedHome();
        $parsedHome->title = $annonce->getName();
        $parsedHome->price = $annonce->getPrice();
        $attributes = $annonce->getAttributes();
        $parsedHome->surface = $attributes[1]->value;
        $parsedHome->rooms = $attributes[2]->value;
        $parsedHome->energy = strtoupper($attributes[3]->value);
        $parsedHome->ges = strtoupper($attributes[4]->value);
        $parsedHome->description = $annonce->getDescription();
        $parsedHome->pictures = $annonce->getImages();
        $location = $annonce->getLocation();
        $parsedHome->city = $location['city'];
        $parsedHome->map = ['lat' => $location['lat'], 'lng' => $location['lng']];

        return $parsedHome;
    }

    /**
     * @param $url
     *
     * @return string
     */
    private function getIdAnnonceFromUrl($url)
    {
        // ex : https://www.leboncoin.fr/ventes_immobilieres/1813996383.htm/
        return collect(explode('.', collect(array_filter(explode('/', $url)))->last()))->first();
    }
}