<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

class MediaResourcesService
{
    protected $connection = null;


    public function __construct()
    {

        $this->connection = DB::connection('mysql-bce');

    }

    /**
     * @param array $mediaIds
     * @return \Illuminate\Support\Collection
     */
    public function getMediaResources(array $mediaIds)
    {
       return $this->connection
           ->table('media_resources')
           ->select(['media_id','met_download_url','video_message'])
           ->whereIn('media_id',$mediaIds)
           ->get();
    }

    /**
     * @param \Illuminate\Support\Collection $mediaResources
     * @param string $filter
     * @return array|\ArrayObject
     */
    public function dealMediaResources(\Illuminate\Support\Collection $mediaResources, $filter = 'met'){

        if(empty($mediaResources)){
            return new \ArrayObject();
        }
        $dealMediaResources = array();

        foreach($mediaResources as $value){

            switch($filter){

                case 'met':
                    if(empty($value->met_download_url)){
                        continue;
                    }
                    $dealMediaResources [$value->media_id] = [
                        'met_download_url' => $value->met_download_url
                    ];
                    break;

                case 'video_message' :

                    $vedioMessage = json_decode($value->video_message,true);

                    if(empty($vedioMessage) || $vedioMessage['status'] != 'PUBLISHED'){
                        continue;
                    }
                    $dealMediaResources [$value->media_id] = [
                        'video_message' => array(
                            'meta' => $vedioMessage['meta'],
                            'attributes' => $vedioMessage['attributes']
                        )
                    ];
                    break;
            }
        }
        return $dealMediaResources;
    }

}