<?php

namespace Lc\ShopBundle\Services;

use Cocur\Slugify\Slugify;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Configuration\ConfigManager;
use Lc\ShopBundle\Context\MerchantUtilsInterface;
use Lc\ShopBundle\Context\PageInterface;
use Lc\ShopBundle\Context\PointSaleInterface;
use Lc\ShopBundle\Context\ReminderInterface;
use Lc\ShopBundle\Context\TaxRateInterface;
use Lc\ShopBundle\Context\UnitInterface;
use Lc\ShopBundle\Context\UserInterface;
use Lc\ShopBundle\Context\UserPointSaleInterface;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

class Utils
{
        protected $em;
        protected $parameterBag;
        protected $merchantUtils;
        protected $session;
        protected $translator;
        protected $configManager;

        const MEAN_PAYMENT_CREDIT_CARD = 'cb';
        const MEAN_PAYMENT_CHEQUE = 'cheque';
        const MEAN_PAYMENT_CREDIT = 'credit';
        const MEAN_PAYMENT_TRANSFER = 'transfer';
        const MEAN_PAYMENT_CASH = 'cash';

        public function __construct(EntityManagerInterface $em, ParameterBagInterface $parameterBag, SessionInterface $session, TranslatorInterface $translator, ConfigManager $configManager, CacheManager $liipCacheHelper)
        {
                $this->em = $em;
                $this->parameterBag = $parameterBag;
                $this->session = $session;
                $this->translator = $translator;
                $this->configManager = $configManager;
                $this->liipCacheHelper = $liipCacheHelper;
        }


        public function getElementByDevAlias($devAlias, $class = PageInterface::class)
        {
                $class = $this->em->getClassMetadata($class)->getName();
                return $this->em->getRepository($class)->findOneByDevAlias($devAlias);
        }


        public function isServerLocalhost()
        {
                return in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']);
        }

        public function getCookieDomain()
        {
                return ($this->isServerLocalhost()) ? null : $this->parameterBag->get('app.cookie_domain_distant');
        }

        public function limitText($text, $limit)
        {
                $text = strip_tags($text);
                if (str_word_count($text, 0) > $limit) {
                        $words = str_word_count($text, 2);
                        $pos = array_keys($words);
                        $text = substr($text, 0, $pos[$limit]) . '...';
                }
                return $text;
        }

        function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
        {
                if ($considerHtml) {
                        // if the plain text is shorter than the maximum length, return the whole text
                        if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length) {
                                return $text;
                        }
                        // splits all html-tags to scanable lines
                        preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
                        $total_length = strlen($ending);
                        $open_tags = array();
                        $truncate = '';
                        foreach ($lines as $line_matchings) {
                                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
                                if (!empty($line_matchings[1])) {
                                        // if it's an "empty element" with or without xhtml-conform closing slash
                                        if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
                                                // do nothing
                                                // if tag is a closing tag
                                        } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
                                                // delete tag from $open_tags list
                                                $pos = array_search($tag_matchings[1], $open_tags);
                                                if ($pos !== false) {
                                                        unset($open_tags[$pos]);
                                                }
                                                // if tag is an opening tag
                                        } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
                                                // add tag to the beginning of $open_tags list
                                                array_unshift($open_tags, strtolower($tag_matchings[1]));
                                        }
                                        // add html-tag to $truncate'd text
                                        $truncate .= $line_matchings[1];
                                }
                                // calculate the length of the plain text part of the line; handle entities as one character
                                $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
                                if ($total_length + $content_length > $length) {
                                        // the number of characters which are left
                                        $left = $length - $total_length;
                                        $entities_length = 0;
                                        // search for html entities
                                        if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
                                                // calculate the real length of all entities in the legal range
                                                foreach ($entities[0] as $entity) {
                                                        if ($entity[1] + 1 - $entities_length <= $left) {
                                                                $left--;
                                                                $entities_length += strlen($entity[0]);
                                                        } else {
                                                                // no more characters left
                                                                break;
                                                        }
                                                }
                                        }
                                        $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
                                        // maximum lenght is reached, so get off the loop
                                        break;
                                } else {
                                        $truncate .= $line_matchings[2];
                                        $total_length += $content_length;
                                }
                                // if the maximum length is reached, get off the loop
                                if ($total_length >= $length) {
                                        break;
                                }
                        }
                } else {
                        if (strlen($text) <= $length) {
                                return $text;
                        } else {
                                $truncate = substr($text, 0, $length - strlen($ending));
                        }
                }
                // if the words shouldn't be cut in the middle...
                if (!$exact) {
                        // ...search the last occurance of a space...
                        $spacepos = strrpos($truncate, ' ');
                        if (isset($spacepos)) {
                                // ...and cut the text in this position
                                $truncate = substr($truncate, 0, $spacepos);
                        }
                }
                // add the defined ending to the text
                $truncate .= $ending;
                if ($considerHtml) {
                        // close all unclosed html-tags
                        foreach ($open_tags as $tag) {
                                $truncate .= '</' . $tag . '>';
                        }
                }
                return $truncate;
        }


        public function isBot()
        {
                if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/bot|crawl|slurp|spider/i', $_SERVER['HTTP_USER_AGENT'])) {
                        return TRUE;
                } else {
                        return FALSE;
                }
        }

        public function slugify($string)
        {
                $slugify = new Slugify();
                return $slugify->slugify($string);
        }

        public function getUnitsList()
        {
                $unitsList = array();
                $units = $this->em->getRepository(UnitInterface::class)->findAll();
                foreach ($units as $unit) {
                        $unitsList[$unit->getId()]['unit'] = $unit->getUnit();
                        $unitsList[$unit->getId()]['wordingUnit'] = $unit->getWordingUnit();
                        $unitsList[$unit->getId()]['wording'] = $unit->getWording();
                        $unitsList[$unit->getId()]['wordingShort'] = $unit->getWordingShort();
                        $unitsList[$unit->getId()]['coefficient'] = $unit->getCoefficient();
                        $unitsList[$unit->getId()]['unitReference'] = $unit->getUnitReference()->getId();
                }

                return $unitsList;
        }


        public function isUserLinkedToPointSale(UserInterface $user, PointSaleInterface $pointSale)
        {
                foreach ($user->getUserPointSales() as $userPointSale) {
                        if ($userPointSale->getPointSale()->getId() == $pointSale->getId()) {
                                return true;
                        }
                }
                return false;
        }

        public function linkUserToPointSale(UserInterface $user, PointSaleInterface $pointSale)
        {
                if (!$this->isUserLinkedToPointSale($user, $pointSale)) {
                        $userPointSaleClass = $this->em->getClassMetadata(UserPointSaleInterface::class)->getName();
                        $userPointSale = new $userPointSaleClass;

                        $userPointSale->setUser($user);
                        $userPointSale->setPointSale($pointSale);

                        $this->em->persist($userPointSale);
                        $this->em->flush();
                }
        }

        function callCitiesApi($method, $url, $data = false)
        {
                $url = 'https://geo.api.gouv.fr/' . $url;
                $curl = curl_init();

                switch ($method) {
                        case "POST":
                                curl_setopt($curl, CURLOPT_POST, 1);

                                if ($data)
                                        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                                break;
                        case "PUT":
                                curl_setopt($curl, CURLOPT_PUT, 1);
                                break;
                        default:
                                if ($data)
                                        $url = sprintf("%s?%s", $url, http_build_query($data));
                }

                // Optional Authentication:
                curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                curl_setopt($curl, CURLOPT_USERPWD, "username:password");

                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

                $result = curl_exec($curl);

                curl_close($curl);

                return $result;
        }

        public function getZipByCity($city, $code = null)
        {
                $zip = null;

                $paramsSearch = [
                        'nom' => $city,
                        'fields' => 'nom,codesPostaux'
                ];

                if ($code != null && $code != 0) {
                        $paramsSearch['code'] = $code;
                }

                $returnCitiesSearchZip = json_decode($this->callCitiesApi('get', 'communes', $paramsSearch));

                if ($returnCitiesSearchZip) {
                        foreach ($returnCitiesSearchZip as $citySearchZip) {
                                if (strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) {
                                        $zip = $citySearchZip->codesPostaux[0];
                                }
                        }
                }

                return $zip;
        }

        public function date($format, $timestamp)
        {
                setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
                return strftime($format, $timestamp);
        }

        public function getNextDay($day)
        {
                return new \DateTime('next ' . $day);
        }

        public function getNextDayByNumber($number)
        {
                return $this->getNextDay($this->getDayByNumber($number, 'en'));
        }

        public function getDayByNumber($number, $lang = 'fr')
        {
                if ($lang == 'fr') {
                        $daysArray = [
                                1 => 'Lundi',
                                2 => 'Mardi',
                                3 => 'Mercredi',
                                4 => 'Jeudi',
                                5 => 'Vendredi',
                                6 => 'Samedi',
                                7 => 'Dimanche'
                        ];
                } else {
                        $daysArray = [
                                1 => 'Monday',
                                2 => 'Tuesday',
                                3 => 'Wednesday',
                                4 => 'Thursday',
                                5 => 'Friday',
                                6 => 'Saturday',
                                7 => 'Sunday',
                        ];
                }

                if (isset($daysArray[$number])) {
                        return $daysArray[$number];
                }

                return '';
        }

        public function addFlash($success, $message, $extraMessages = array(), $params = array(), $domain = 'lcshop')
        {
                $message = $this->translator->trans($message, $params, $domain);

                if (count($extraMessages)) {
                        $message .= '<ul>';
                        foreach ($extraMessages as $extraMessage) {
                                $message .= '<li> <i>' . $this->translator->trans($extraMessage, array(), $domain) . '</i></li>';
                        }
                        $message .= '</ul>';
                }

                $this->session->getFlashBag()->add($success, $message);

        }

        public function getFlashMessages()
        {
                return $this->session->getFlashBag()->all();
        }

        function camelCase($str)
        {
                $i = array("-", "_");
                $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
                $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
                $str = str_replace($i, ' ', $str);
                $str = str_replace(' ', '', ucwords(strtolower($str)));
                $str = strtolower(substr($str, 0, 1)) . substr($str, 1);
                return $str;
        }

        function snakeCase($str)
        {
                $str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
                $str = strtolower($str);
                return $str;
        }

        public function csvEscape($str)
        {
                return str_replace(array("\r", "\n"), ' ', $str);
        }

        public function getRemindersByUser($user)
        {
                $reminderRepo = $this->em->getRepository(ReminderInterface::class);


                $reminders = $reminderRepo->findByUser($user);

                $entitiesRepo = array();
                $entitiesConfig = array();
                if (count($reminders) > 0) {
                        foreach ($reminders as $reminder) {
                                if ($reminder->getEntityName()) {
                                        if (!isset($entitiesConfig[$reminder->getEntityName()])) {
                                                $entitiesConfig[$reminder->getEntityName()] = $this->configManager->getEntityConfig($reminder->getEntityName());
                                        }
                                        if ($reminder->getEntityAction() == 'edit' || $reminder->getEntityAction() == 'show') {
                                                if (!isset($entitiesRepo[$reminder->getEntityName()])) {
                                                        $entitiesRepo[$reminder->getEntityName()] = $this->em->getRepository($entitiesConfig[$reminder->getEntityName()]['class']);
                                                }

                                                if ($reminder->getEntityId()) {
                                                        $reminder->relatedPage = $entitiesRepo[$reminder->getEntityName()]->find($reminder->getEntityId())->__toString();
                                                }
                                        } else {
                                                $reminder->relatedPage = 'Liste de ' . $entitiesConfig[$reminder->getEntityName()]['label'];
                                        }
                                }
                        }
                }
                return $reminders;
        }

        public function removeDir($dir)
        {
                $files = array_diff(scandir($dir), array('.', '..'));
                foreach ($files as $file) {
                        (is_dir("$dir/$file")) ? $this->removeDir("$dir/$file") : unlink("$dir/$file");
                }
                return rmdir($dir);
        }

        function folderToZip($folder, &$zipFile, $subfolder = null)
        {
                if ($zipFile == null) {
                        // no resource given, exit
                        return false;
                }
                // we check if $folder has a slash at its end, if not, we append one
                $tabFolder = str_split($folder);
                $tabSubFolder = str_split($subfolder);
                $folder .= end($tabFolder) == "/" ? "" : "/";
                $subfolder .= end($tabSubFolder) == "/" ? "" : "/";
                // we start by going through all files in $folder
                $handle = opendir($folder);
                while ($f = readdir($handle)) {
                        if ($f != "." && $f != "..") {
                                if (is_file($folder . $f)) {
                                        // if we find a file, store it
                                        // if we have a subfolder, store it there
                                        if ($subfolder != null)
                                                $zipFile->addFile($folder . $f, $subfolder . $f);
                                        else
                                                $zipFile->addFile($folder . $f);
                                } elseif (is_dir($folder . $f)) {
                                        // if we find a folder, create a folder in the zip
                                        $zipFile->addEmptyDir($f);
                                        // and call the function again
                                        folderToZip($folder . $f, $zipFile, $f);
                                }
                        }
                }
        }

        public function lcLiip($path, $thumb = 'tile', $default = 'default.jpg')
        {
                if (substr($path, 0, 1) === '/') $path = substr($path, 1);

                if ($path) {
                        $fileManagerFolder = substr($this->getFileManagerFolder(), 1)  ;

                        if (strpos($path, $fileManagerFolder) === false) {
                                $path = $fileManagerFolder . '/' . $path;
                        }

                        if (file_exists($path)) {
                                return $this->liipCacheHelper->getBrowserPath($path, $thumb);
                        }
                }

                return $this->liipCacheHelper->getBrowserPath($this->getFileManagerFolder() . '/' . $default, $thumb);
        }

        /**
         * Retourne le chemin vers le dossier d'uploads de responsiveFilemanager
         *
         * @return string
         */
        public function getFileManagerFolder()
        {
                return $this->parameterBag->get('app.path.images');
        }

}
