<?php

namespace Lc\ShopBundle\Services;

use Cocur\Slugify\Slugify;
use Doctrine\ORM\EntityManagerInterface;
use Lc\ShopBundle\Context\MerchantUtilsInterface;
use Lc\ShopBundle\Context\PageInterface;
use Lc\ShopBundle\Context\PointSaleInterface;
use Lc\ShopBundle\Context\TaxRateInterface;
use Lc\ShopBundle\Context\UnitInterface;
use Lc\ShopBundle\Context\UserInterface;
use Lc\ShopBundle\Context\UserPointSaleInterface;
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;

        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)
        {
                $this->em = $em ;
                $this->parameterBag = $parameterBag ;
                $this->session = $session;
                $this->translator = $translator;
        }


        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)
        {
                $zip = null ;
                $returnCitiesSearchZip = json_decode($this->callCitiesApi('get', 'communes', ['nom' => $city, 'fields' => 'nom,codesPostaux'])) ;

                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();
        }
}