<?php

namespace App\Controllers;

use App\Controllers\Base\UserBaseController;
use App\Repositories\HidePostRepository;
use App\Repositories\PostRepository;

/**
*
*@author : Tiamiyu waliu
*@website : http://www.iDocrea8.com
*/
class PostController extends UserBaseController
{
    public function __construct(PostRepository $postRepository, HidePostRepository $hidePostRepository)
    {
        parent::__construct();
        $this->postRepository = $postRepository;
        $this->hidePost = $hidePostRepository;
    }

    public function index($id)
    {
        $post = $this->postRepository->findById($id);

        if (!$post) return $this->theme->section('error-page');

        $ad = (empty($post->text)) ? trans('post.post')  : str_limit($post->text,60);
        return $this->render('post.page', ['post' => $post],
            [
                'title' => $this->setTitle($ad),
                'design' => $post->user->present()->readDesign()

            ]
        );
    }

    public function loadLinkPreview()
    {
        $link = \Input::get('link');
        $link = str_replace(['http://', 'https://'], ['', ''], $link);
        $link = 'http://'.$link;
        $result = $this->postRepository->getLinkDetails($link, true);
        $result['preview'] = (String) $this->theme->section('post.editor.link-preview', ['result' => $result]);

        return json_encode($result);
    }

    public function searchMedia()
    {
        $v = \Input::get('v');
        $type = \Input::get('type');

        if ($type == 'audio') {
            $soundcloud = 'http://api.soundcloud.com/tracks.json?client_id=e8d2797b62ce47938f3baa699a725864&limit=5&q=' . urlencode($v);

            $soundcloud = @file_get_contents($soundcloud);


            $results = json_decode($soundcloud, true);


            $a = [];
            if (is_array($results) and count($results) > 1) {
                foreach($results as $s) {

                    if ($s['kind'] == 'track') {
                        $a[] = [
                            'title' => $s['title'],
                            'description' => $s['description'],
                            'link' => $s['uri'],
                            'image' => $s['artwork_url']
                        ];
                    }
                }

                return $this->theme->section('post.format-media-search', ['medias' => $a]);
            } else {
                //return (string) trans('post.no-result-found');
            }
        } elseif ($type == 'video') {
            $youtube = 'http://gdata.youtube.com/feeds/api/videos?q=' . urlencode($v) . '&max-results=5&orderby=relevance&alt=json&format=5&v=2';
            $youtube = @file_get_contents($youtube);
            $results = json_decode($youtube, true);

            if ($results) {
                $a = [];
                foreach($results['feed']['entry'] as $y) {
                    $l = $y['media$group']['yt$videoid']['$t'];
                    $l = "http://www.youtube.com/embed/".$l;
                    $a[] = [
                        'title' => $y['title']['$t'],
                        'link' => (String) $l,
                        'image' => $y['media$group']['media$thumbnail'][1]['url']
                    ];
                }


                return $this->theme->section('post.format-media-search', ['medias' => $a]);
            } else {

            }
        }


    }


    public function add()
    {
        if ($post = $this->postRepository->add(\Input::get('val'))) {

            return (String) $this->theme->section('post.media', ['post' => $post]);
        }

        return 0;
    }

    public function edit($id)
    {
        $text = \Input::get('text');

        $post = $this->postRepository->updateText($id, $text);

        if ($post) {
            return $post->present()->text();
        }
    }

    public function uploadImage()
    {
        $result = [
            'code' => 0,
            'message' => trans('post.post-image-error')
        ];
        if ($image = \Input::file('image')) {
            $uploadImage = $this->postRepository->uploadImage($image);

            if ($uploadImage) {
                $result['image'] = $uploadImage;
                $result['imageurl'] = \Image::url($uploadImage, 100);
                $result['code'] = 1;
            }
        }

        return json_encode($result);
    }

    public function share($id)
    {
        if ($count = $this->postRepository->share($id)) {
            return json_encode([
                'code' => 1,
                'count' => $count
            ]);
        }

        return json_encode([
            'code' => 0,
            'message' => 'Failed to share post, please try again'
        ]);
    }

    public function delete($id)
    {
        $this->postRepository->delete($id);
    }

    public function hide($id)
    {
        $this->hidePost->add($id);

        return $this->theme->section('post.hide');
    }

    public function unHide($id)
    {
        $this->hidePost->remove($id);
    }

    public function loadShares($id)
    {
        if (\Request::ajax()) {
            return $this->theme->section('post.shares.inline', ['posts' => $this->postRepository->getShares($id)]);
        }
    }

    public function paginate()
    {
        $type = \Input::get('type');
        $offset = \Input::get('offset');
        $userid = \Input::get('userid');
        $offset = (empty($offset)) ? \Config::get('post-per-page') : $offset;
        $newOffset = $offset  + (int) \Config::get('post-per-page');


        return json_encode([
            'offset' =>$newOffset,
            'posts' => (String)  $this->theme->section('post.paginate', ['posts' => $this->postRepository->lists($type, $offset, $userid)])
        ]);
    }

}