<?php

namespace App\Listeners;

use App\Events\EachLike;
use App\Events\ThumbUser;
use App\Events\UnEachLike;
use App\Events\UnThumbUser;
use App\Models\PartnerModel;
use App\Models\PraiseModel;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class ThumbOrUnThumbUser
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
    }

    public function thumb(ThumbUser $event)
    {
        PraiseModel::updateOrCreate([
            'uid' => $event->user->uid,
            'partner_id' => $event->partner->id
        ], [
            'type' => 1,
            'updated_at' => $event->timestamp,
            'read' => 0
        ]);
        PartnerModel::where('id', $event->partner->id)->increment('praises', 1);
        if (
            PraiseModel::where([
                array('uid', $event->partner->uid), array('partner_id', $event->user->partner_id), array('type', 1)
            ])->first()
        ) {
            PraiseModel::where([
                array('uid', $event->user->uid), array('partner_id', $event->partner->id)
            ])->orWhere([
                array('uid', $event->partner->uid), array('partner_id', $event->user->partner_id)
            ])->update(['lock' => 100]);
            event(new EachLike($event->user->uid, $event->partner->uid));
        }
    }

    public function unThumb(UnThumbUser $event)
    {
        if (
            PraiseModel::where([
                array('uid', $event->partner->uid), array('partner_id', $event->user->partner_id), array('type', 1)
            ])->first()
        ) {
            event(new UnEachLike($event->user->uid, $event->partner->uid));
        }
        PraiseModel::where([
            array('uid', $event->user->uid), array('partner_id', $event->partner->id)
        ])->update([
            'type' => 0,
            'updated_at' => $event->timestamp
        ]);
    }
}
