<?php namespace App\Console\Commands;

use App\Services\Mail\PostmarkTransport;
use Formatter;
use Illuminate\Console\Command;
use Tobuli\Entities\DeviceService;
use Tobuli\Entities\EmailTemplate;
use Tobuli\Entities\SmsTemplate;

use Bugsnag\BugsnagLaravel\BugsnagFacade as Bugsnag;


class CheckServiceExpireCommand extends Command
{
    /**
     * The console command name.
     * @var string
     */
    protected $name = 'service:check_expire';

    /**
     * The console command description.
     * @var string
     */
    protected $description = 'Check for service expired.';

    private $emailTemplate;
    private $smsTemplate;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->smsTemplate = SmsTemplate::where('name', 'service_expired')->first();
        $this->emailTemplate = EmailTemplate::where('name', 'service_expired')->first();

        $services = DeviceService::expireByDays('device_services.expires_date')
            ->notExpired()
            ->get();

        foreach ($services as $service)
            $this->processItem($service);


        $services = DeviceService::expireByOdometer('device_services.expires')
            ->notExpired()
            ->get();

        foreach ($services as $service)
            $this->processItem($service);


        $services = DeviceService::expireByEngineHours('device_services.expires')
            ->notExpired()
            ->get();

        foreach ($services as $service)
            $this->processItem($service);


        return 'DONE';
    }

    protected function processItem($service)
    {
        if ($service->user)
            Formatter::byUser($service->user);
        else
            Formatter::byDefault();

        try {
            sendTemplateEmail($service->email, $this->emailTemplate, $service);
        } catch (\Exception $e) {
            Bugsnag::notifyException($e);
        }

        try {
            sendTemplateSMS($service->mobile_phone, $this->smsTemplate, $service, $service->user_id);
        } catch (\Exception $e) {
            Bugsnag::notifyException($e);
        }

        if ( ! $service->renew_after_expiration)
        {
            $service->update([
                'expired' => 1
            ]);

            return;
        }

        switch ($service->expiration_by) {
            case 'odometer':
                $sensor = $service->device->getOdometerSensor();
                $values = $sensor ? ['odometer' => $sensor->getValueCurrent($service->device->other)] : [];
                break;

            case 'engine_hours':
                $sensor = $service->device->getEngineHoursSensor();
                $values = $sensor ? ['engine_hours' => $sensor->getValueCurrent($service->device->other)] : [];
                break;

            default:
                $values = [];
        }

        $update = prepareServiceData($service->toArray(), $values);
        $update = array_only($update, $service->getFillable());

        $service->update($update);

        return null;
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array();
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array();
    }
}
