<?php

namespace App\Helpers;

use Illuminate\Support\Str;

/**
 * String operations helper.
 * v2
 */
class StringOperation
{

    public static function disableHtmlTags($string)
    {
        $string = str_replace(['<', '>'], ['&lt;', '&gt;'], $string);
        return $string;
    }

    public static function enableHtmlTags($string)
    {
        $string = str_replace(['&lt;', '&gt;'], ['<', '>'], $string);
        return $string;
    }

    public static function safeText($string)
    {
        return nl2br(self::disableHtmlTags($string));
    }

    /**
     * Function used to generate path basesd on ids.
     * @param type $num
     * @return type
     */
    public static function convertNumberToPath($num, $addNumAsFolder = false)
    {
        // adds trailing zeros converts 3 to 000000003
        $result = str_pad($num, 9, 0, STR_PAD_LEFT); // eq of sprintf('%09d', $num);
        // adds "/" after each 3 chars
        $result = wordwrap($result, 3, '/', true);
        // remove last 3 chars, since we want to store 999 files.
        $result = substr($result, 0, -3);
        // sometimes we want in the save the resource to an id
        if ($addNumAsFolder) {
            $result .= $num . '/';
        }
        return $result;
    }

    /**
     * Function used to generate path basesd on ids.
     * @param type $num
     * @return type
     */
    public static function getCompletePath($num, $namespace = 'users', $with_filename = true)
    {
        return public_path('storage/' . $namespace . '/' . $num . '/' . ($with_filename ? $num . '.jpg' : ''));
        return public_path('storage/' . $namespace . '/' . self::convertNumberToPath($num) . ($with_filename ? $num . '.jpg' : ''));
    }

    /**
     * Function used to generate path basesd on ids.
     * @param type $num
     * @return type
     */
    public static function getCompletePathUsers($num, $with_filename = true)
    {
        return self::getCompletePath($num, config('paths.users'), $with_filename);
    }

    public static function getCompletePathFromNumber($num, $namespace = 'general', $with_filename = true)
    {
        return self::getCompletePath(self::convertNumberToPath($num, true), config('paths.' . $namespace), $with_filename);
    }

    public static function getPhotoUrlFromNumber($num, $namespace = 'general', $filename, $show_thumb = false)
    {
        return asset('storage/' . config('paths.' . $namespace) . '/' . self::convertNumberToPath($num, true) . ($show_thumb ? 'thumb_' : '') . $filename);
    }




//    public static function getCompletePathPhotos($num, $with_filename = true)
//    {
//        return self::getCompletePath(self::convertNumberToPath($num, true), config('paths.photos'), $with_filename);
//    }

    public static function getCompletePathCategories($num, $with_filename = true)
    {
        return public_path('storage/' . config('paths.categories') . '/' . ($with_filename ? $num . '.png' : ''));
    }

    public static function getCompletePathCity($num)
    {
        return public_path('storage/' . config('paths.categories'));
    }

    public static function getCompletePathDocuments($num)
    {
        return public_path('storage/' . config('paths.documents') . '/' . self::convertNumberToPath($num, true));
    }

    public static function getCompletePathCovers($file = null)
    {
        return public_path('storage/' . config('paths.covers')) . '/' . $file;
    }

    public static function getCompletePathCommentPhotos($num = null, $with_filename = true)
    {
        return self::getCompletePathFromNumber($num, config('paths.comments'), $with_filename);
    }

    /**
     *
     *
     * @param type $text
     * @param type $delimiter
     * @return type
     */
    public static function getSearchableText($text, $delimiter = '%')
    {
        $text = trim($text);
        $text = str_replace(' ', $delimiter, $text);
        return $delimiter . $text . $delimiter;
    }

    public static function words($text, $separator = ' ')
    {
        // remove chars that are not within the whitelist
        $text = preg_replace('#[^\pL\pN@\.\-_\+]#ius', ' ', $text);
        // remove multiple spaces
        $text = preg_replace('#[\s]{2,}#', ' ', $text);
        // replace @ with _at_
        $text = str_replace('@', '_at_', $text);
        // replace spaces with separator blalblablas
        $text = preg_replace('#\s#', $separator, $text);
        return $text;
    }

    public static function text_limit($text, $words_limit = 70)
    {
        // some paragrpahs don't have space, dot after last word.
        $text = str_replace('>', '> ', $text);
        $text = strip_tags($text, '<br>');
        $text = str_replace('<br>', ' ', $text);
        // get number of rows
        $text = str_replace(['<br/>', '<br />'], '<br>', $text);
        $rows = explode('<br>', $text);
        if ($rows > 3) {
            $text = implode('<br>', array_slice($rows, 0, 3));
        }

        return Str::words($text, $words_limit);
    }

    /**
     * (c) Søren Løvborg
     *
     * https://stackoverflow.com/a/1193598/1894856
     *
     * @param $html
     * @param $maxLength
     * @param bool $isUtf8
     * @return string
     */
    public static function truncateWithTags($html, $appendHtml = '', $percent = 0.75, $isUtf8 = true)
    {
        // get the length of the text after stripting htmnl
        $totalLength = mb_strlen(strip_tags($html));
        $maxLength = $totalLength * $percent;

        $printedLength = 0;
        $position = 0;
        $tags = array();
        $text = '';

        // For UTF-8, we need to count multibyte sequences as one character.
        $re = $isUtf8
            ? '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;|[\x80-\xFF][\x80-\xBF]*}'
            : '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}';

        while ($printedLength < $maxLength && preg_match($re, $html, $match, PREG_OFFSET_CAPTURE, $position)) {
            list($tag, $tagPosition) = $match[0];

            // Print text leading up to the tag.
            $str = substr($html, $position, $tagPosition - $position);
            if ($printedLength + strlen($str) > $maxLength) {
                $text .= (substr($str, 0, $maxLength - $printedLength));
                $printedLength = $maxLength;
                break;
            }

            $text .= ($str);
            $printedLength += strlen($str);
            if ($printedLength >= $maxLength) break;

            if ($tag[0] == '&' || ord($tag) >= 0x80) {
                // Pass the entity or UTF-8 multibyte sequence through unchanged.
                $text .= ($tag);
                $printedLength++;
            } else {
                // Handle the tag.
                $tagName = $match[1][0];
                if ($tag[1] == '/') {
                    // This is a closing tag.

                    $openingTag = array_pop($tags);
                    assert($openingTag == $tagName); // check that tags are properly nested.

                    $text .= ($tag);
                } else if ($tag[strlen($tag) - 2] == '/') {
                    // Self-closing tag.
                    $text .= ($tag);
                } else {
                    // Opening tag.
                    $text .= ($tag);
                    $tags[] = $tagName;
                }
            }

            // Continue after the tag.
            $position = $tagPosition + strlen($tag);
        }

        // Print any remaining text.
        if ($printedLength < $maxLength && $position < strlen($html))
            $text .= (substr($html, $position, $maxLength - $printedLength));

        $text .= '...' . $appendHtml;

        // Close any open tags.
        while (!empty($tags))
            $text .= sprintf('</%s>', array_pop($tags));

        return $text;
    }


    public static function extractText($text)
    {
        $text = html_entity_decode($text);
        $text = (preg_replace("#[\s\t]{2,}#mu", " ", $text));
        return strip_tags(str_replace('<', ' <', $text));
    }

}
