<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\HttpKernel\KernelInterface;

use Symfony\Component\Finder\Finder;

class ThemeController extends AbstractController
{
    private $appKernel;

    public function __construct(KernelInterface $appKernel)
    {
        $this->appKernel = $appKernel;
    }

    public function list(Request $request)
    {
        $session=$request->getSession();
        $finder = new Finder();

        $dir = $this->appKernel->getProjectDir()."/public/themes";

        $finder->in($dir)->directories()->depth('== 0');
        $themes=[];
        $themes[""]["dir"]="";
        $themes[""]["name"]="Thème par défaut";

        foreach ($finder as $file) {
            $key=$file->getRelativePathname();
            $themes[$key]["dir"]=$key;

            $yml=Yaml::parseFile($dir.'/'.$key.'/info.yml');
            $themes[$key]["name"]=$yml["name"];
        }
        
        $current=$session->get("theme");
        $currentheme=$themes[$current];
        unset($themes[$current]);

        return $this->render('Theme\list.html.twig',[
            'useheader'     => true,
            'usemenu'       => false,
            'usesidebar'    => true,
            'currentheme'   => $currentheme,
            'themes'        => $themes
        ]);
    }   

    public function select($name, Request $request, ManagerRegistry $em)
    {
        $config=$em->getRepository("App\Entity\Config")->findoneBy(["id"=>"theme"]);
        $config->setValue($name);

        $em->getManager()->flush();        

        return $this->redirectToRoute("app_core_config_theme");
    }

    public function setconfig(Request $request)
    {
        $session=$request->getSession();
        $themename=$session->get("theme");

        $logo=$request->query->get('logo');
        if(!empty($logo)) $session->set('logo',"themes/$themename/".$logo);
       
        $header=$request->query->get('header');
        if(!empty($header)) $session->set('header',"themes/$themename/".$header);

        $heightheader=$request->query->get('heightheader');
        if(!empty($heightheader)) $session->set('heightheader',$heightheader);
        
        $colormain=$request->query->get('colormain');
        if(!empty($colormain)) $session->set('colormain',$colormain);        

        $fontcolorhover=$request->query->get('fontcolorhover');
        if(!empty($fontcolorhover)) $session->set('fontcolorhover',$fontcolorhover);   

        $colorbody=$request->query->get('colorbody');
        if(!empty($colorbody)) $session->set('colorbody',$colorbody);    

        $fontfacetitle=$request->query->get('fontfacetitle');
        if(!empty($fontfacetitle)) $session->set('fontfacetitle',$fontfacetitle);        

        $fontfacebody=$request->query->get('fontfacebody');
        if(!empty($fontfacebody)) $session->set('fontfacebody',$fontfacebody);        

        $this->setColor($session);

        return new Response();
    }


    public function setColor($session) {
        $colormain      =$session->get('colormain');
        $colorlight     =$this->adjustBrightness($colormain,+50);
        $colordark      =$this->adjustBrightness($colormain,-50);
        $colormainrgb   =$this->hexToRgb($colormain);
        $colorlightrgb  =$this->hexToRgb($colorlight);
        $colordarkrgb   =$this->hexToRgb($colordark);        

        $fontcolorhover =$session->get('fontcolorhover');
        $colorbody      =$session->get('colorbody');

        $tbcolor=array(
            "main"                  =>$colormain,
            "light"                 =>$this->adjustBrightness($colormain,+50),
            "dark"                  =>$this->adjustBrightness($colormain,-50),
            "mainrgb"               =>$this->hexToRgb($colormain),
            "lightrgb"              =>$this->hexToRgb($colorlight),
            "darkrgb"               =>$this->hexToRgb($colordark),

            "fontcolorhover"        =>$fontcolorhover,
            "fontcolorhoverlight"   =>$this->adjustBrightness($fontcolorhover,+50),
            "fontcolorhoverdark"    =>$this->adjustBrightness($fontcolorhover,-50),

            "colorbody"             =>$colorbody,
        );
        
        $session->set('color', $tbcolor);
    }

    public function adjustBrightness($hex, $steps) {
        // Steps should be between -255 and 255. Negative = darker, positive = lighter
        $steps = max(-255, min(255, $steps));

        // Normalize into a six character long hex string
        $hex = str_replace('#', '', $hex);
        if (strlen($hex) == 3) {
            $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
        }

        // Split into three parts: R, G and B
        $color_parts = str_split($hex, 2);
        $return = '';

        foreach ($color_parts as $color) {
            $color   = hexdec($color); // Convert to decimal
            $color   = max(0,min(255,$color + $steps)); // Adjust color
            $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
        }

        return $return;
    }

    public function hexToRgb($hex) {
       $hex      = str_replace('#', '', $hex);
       $length   = strlen($hex);
       $rgb['r'] = hexdec($length == 6 ? substr($hex, 0, 2) : ($length == 3 ? str_repeat(substr($hex, 0, 1), 2) : 0));
       $rgb['g'] = hexdec($length == 6 ? substr($hex, 2, 2) : ($length == 3 ? str_repeat(substr($hex, 1, 1), 2) : 0));
       $rgb['b'] = hexdec($length == 6 ? substr($hex, 4, 2) : ($length == 3 ? str_repeat(substr($hex, 2, 1), 2) : 0));

       return $rgb;
   }      
}
