<?php

namespace App\Http\Resources;

use App\Helpers\Helper;
use Illuminate\Http\Resources\Json\JsonResource;
use ImageCross;

class CommentResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id'               => $this->id,
            'idx'              => $this->idx,
            'image'            => $this->image,
            'like'             => $this->like,
            'dislike'          => $this->dislike,
            'author'           => $this->author,
            'is_anonymous'     => $this->is_anonymous,
            'is_show_id'       => $this->is_show_id,
            'is_allow_comment' => $this->is_allow_comment,
            'commentCount'     => $this->commentCount,
            'gate'             => $this->gate,
            'plus'             => $this->plus,
            'minus'            => $this->minus,
            'loadingPlus'      => $this->loadingPlus,
            'loadingMinus'     => $this->loadingMinus,
            'detail'           => array_map(
                function ($detail) {
                    return [
                        'comment_id'  => $detail['comment_id'],
                        'content'     => Helper::filterAll($detail['content']),
                        'title'       => $detail['title'],
                        'domain'      => $detail['domain'],
                        'description' => $detail['description'],
                        'thumbnail'   => $detail['thumbnail'],
                        'is_url'      => $detail['is_url'],
                    ];
                },
                $this->detail->toArray()
            ),
            'quote'            => array_map(
                function ($quote) {
                    return [
                        'id'         => $quote['id'],
                        'parent_id'  => $quote['parent_id'],
                        'comment_id' => $quote['comment_id'],
                        'content'    => $quote['content'],
                    ];
                },
                $this->quote->toArray()
            ),
            'created_at'       => date('Y-m-d H:i:s', strtotime($this->created_at)),
        ];
    }

    public static function saveImage($file)
    {
        try {
            $filePath = public_path('uploads/image/topic');
            $fileName = md5(date('YmdHis') . rand(1, 9999)) . '.jpg';
            ImageCross::make($file)->orientate()->save($filePath . '/' . $fileName);
            return $fileName;
        } catch (\Exception $exception) {
            return "";
        }
    }

    public static function createThumb($file, $width = 60, $height = 60)
    {
        try {
            $filePath = public_path('uploads/image/topic');
            $fileName = md5(date('YmdHis') . rand(1, 9999)) . '.jpg';
            $imgCross = ImageCross::make($file)->orientate()->save($filePath . '/' . $fileName);
            $imgCross->resize(60, 60, function ($constraint) {
                $constraint->aspectRatio();
                $constraint->upsize();
            })->save($filePath . '/thumbnail_60x60/' . $fileName);
            return $fileName;
        } catch (\Exception $exception) {
            return "";
        }
    }

    public static function getMetaInfo($url = "")
    {
        $domain = null;
        $title = null;
        $metaTags = [];
        $images = [];
        $metaList = ['og:image', 'og:image:secure_url', 'twitter:url', 'twitter:title', 'twitter:image', 'twitter:description', 'description'];

        if ($url != "") {
            $contents = self::getUrlContents($url);
            $protocol = 'http://';
            if (strpos($url, "https://") !== false) $protocol = "https://";

            $domain = str_replace("https://", "", $url);
            $domain = str_replace("http://", "", $domain);
            $domainOrigin = str_replace("www.", "", $domain);
            if (strpos($domainOrigin, "/") !== false) {
                $domain = explode("/", $domainOrigin);
                $domain = (count($domain) > 0) ? $domain[0] : $domainOrigin;
            }

            if (isset($contents) && is_string($contents)) {
                preg_match('/<title>([^>]*)<\/title>/si', $contents, $match);
                if (isset($match) && is_array($match) && count($match) > 0) {
                    $title = strip_tags($match[1]);
                }

                preg_match_all('/<[\s]*meta[\s]*name="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);
                if (isset($match) && is_array($match) && count($match) == 3) {
                    $originals = $match[0];
                    $names = $match[1];
                    $values = $match[2];
                    if (count($originals) == count($names) && count($names) == count($values)) {
                        for ($i = 0, $limiti = count($names); $i < $limiti; $i++) {
                            if (in_array($names[$i], $metaList)) {
                                $metaKey = str_replace(":", "_", $names[$i]);
                                $metaTags[$metaKey] = $values[$i]; //htmlentities($originals[$i])
                            }
                        }
                    }
                }

                preg_match_all('/<[\s]*meta[\s]*property="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);
                if (isset($match) && is_array($match) && count($match) == 3) {
                    $originals = $match[0];
                    $names = $match[1];
                    $values = $match[2];
                    if (count($originals) == count($names) && count($names) == count($values)) {
                        for ($i = 0, $limiti = count($names); $i < $limiti; $i++) {
                            if (in_array($names[$i], $metaList)) {
                                $metaKey = str_replace(":", "_", $names[$i]);
                                $metaTags[$metaKey] = $values[$i]; //htmlentities($originals[$i])
                            }
                        }
                    }
                }

                if (isset($metaTags['og_image']) && $metaTags['og_image'] != "") {
                    $images[] = ['data_src' => $metaTags['og_image'], 'src_set' => '', 'src' => ''];
                }

                $htmlDom = new \DOMDocument();
                @$htmlDom->loadHTML($contents);
                $imageTags = $htmlDom->getElementsByTagName('img');
                foreach ($imageTags as $imageTag) {
                    $imgDataSrc = $imageTag->getAttribute('data-src');
                    $imgDataSrc = (strpos($imgDataSrc, "/") !== false && strpos($imgDataSrc, "/") == 0) ? $protocol . $domain . $imgDataSrc : $imgDataSrc;
                    $imgDataSrc = trim($imgDataSrc);
                    $imgSrcSet = $imageTag->getAttribute('srcset');
                    $imgSrcSet = (strpos($imgDataSrc, "/") !== false && strpos($imgSrcSet, "/") == 0) ? $protocol . $domain . $imgSrcSet : $imgSrcSet;
                    $imgSrcSet = trim($imgSrcSet);
                    $imgSrc = $imageTag->getAttribute('src');
                    $imgSrc = (strpos($imgDataSrc, "/") !== false && strpos($imgSrc, "/") == 0) ? $protocol . $domain . $imgSrc : $imgSrc;
                    $imgSrc = trim($imgSrc);

                    if ((!empty($imgDataSrc) && strpos($imgDataSrc, "http") !== false) ||
                        (!empty($imgSrcSet) && strpos($imgSrcSet, "http") !== false) ||
                        (!empty($imgSrc) && strpos($imgSrc, "http") !== false)) {
                        $images[] = array(
                            'data_src' => $imgDataSrc,
                            'src_set'  => $imgSrcSet,
                            'src'      => $imgSrc,
                        );
                    }
                }
                unset($imageTags);
                unset($htmlDom);
            }
        }

        return [
            'domain'   => $domain,
            'title'    => $title,
            'metaTags' => $metaTags,
            'images'   => $images,
        ];
    }

    public static function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
    {
        $result = false;
        $contents = @file_get_contents($url);
        if (isset($contents) && is_string($contents)) {
            preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);
            if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1) {
                if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections) {
                    return self::getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
                }
                $result = false;
            } else {
                $result = $contents;
            }
        }
        return $contents;
    }
}
