<?php

namespace App\Http\Controllers;

use App;
use File;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Collection;
use App\Requests\TranslationRequest;


class TranslationFileController extends Controller
{


    /**
     * Translator
     *
     * @var \Illuminate\Translation\Translator
     */
    protected $translator;
    /**
     * Translation loader
     *
     * @var \Illuminate\Translation\LoaderInterface
     */
    protected $loader;

    /**
     * @var \League\Flysystem\Adapter\Local
     */
    protected $filesystem;

    /**
     * @var string
     */
    protected $languagesPath;

    protected $languageRead;




    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

        $this->directory_separator = DIRECTORY_SEPARATOR;
        $this->translator = App::make('translator');
        $this->loader = Lang::getLoader();
        $this->languagesPath = App::langPath();
        $this->directory_separator = DIRECTORY_SEPARATOR;
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $language =  App::getLocale();
        $langsource = 'de';
        $this->languageRead = $language;
        $langs = array_keys(config('localization.supportedLocales'));
        $files = $this->files();
        $translations = null;
        $edit = false;
        $show = 'all';
        return view('translation.index_file', compact('files', 'translations', 'language', 'langsource', 'langs', 'edit', 'show'));

        //return view('admin.transitions', $data);
    }

    /**
     * Display edit form page
     *
     * @param string      $language
     * @param string      $file
     * @param string|null $namespace
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($file, $language = 'en', $langsource = 'de', $show = 'all')
    {
        $this->languageRead = $language;
        $langs = array_keys(config('localization.supportedLocales'));
        $files = $this->files();
        $translations = $this->translations($file, $langsource);
        $prefix = $this->groupName($file);
        $langsource = $langsource;
        $edit = $file;
        $show = $show;

        return view('translation.index_file', compact('files', 'language', 'langsource', 'file', 'translations', 'prefix', 'langs', 'edit', 'show'));
    }

    /**
     * Save translation file
     *
     * @param \GeniusTS\TranslationManager\Requests\TranslationRequest $request
     * @param string                                                   $language
     * @param string                                                   $file
     *
     * @return \Illuminate\Http\Response
     */
    public function update(TranslationRequest $request, $file, $language, $langsource, $show)
    {
        $keys = array_keys($this->translations($file));

        $this->exportFile($request->only($keys), $file, $language);

        return redirect()
            ->route('admin_translate_file_edit', [$file, $language, $langsource, $show])
            ->with('message', 'Translation added successfully');
    }

    /**
     * Save a translation file
     *
     * @param array $translation
     * @param       $filename
     * @param       $language
     *
     * @return bool
     */
    public function exportFile($translation, $filename, $language)
    {
        $path = "{$this->languagesPath}{$this->directory_separator}{$language}{$this->directory_separator}{$filename}.php";

        $this->backup($path, $language, $filename);

        $content = "<?php \n\n return " . var_export($translation, true) . ";";

        return (bool) file_put_contents($path, $content);

        //return (bool) $this->filesystem->write($path, $content, new Config);
    }

    /**
     * Backup the existing translation files
     */
    private function backup($path, $language, $filename)
    {
        if(!File::exists($path)){
            return;
        }
        if (!File::exists(storage_path('language/'.time().'/'.$language))) {
            File::makeDirectory(storage_path('language/'.time().'/'.$language), 0755, true);
        }

        return File::copy($path, storage_path('language/'.time().'/'.$language.'/'.$filename.'.php'));
    }


    /**
     * Get the translation of a group and name space
     *
     * @param string      $file
     * @param string|null $namespace
     * @param string|null $language
     *
     * @return array
     */
    public function translations($file, $language = null)
    {
        $group = $this->groupName($file);
        $key = $group;

        return $this->translator->trans($key, [], $language ?: $this->defaultLanguage());
    }

    public function files($lang = false)
    {
        $path = $this->namespacePath($this->languagesPath, $lang);

        $content = $this->pathContent($path);

        return $content
            ->map(function ($file) use ($path) {
                $path = ltrim($path . DIRECTORY_SEPARATOR, '/');
                //read file empty entries
                $count = $this->countEmptyEntries(Str::replaceLast($path, '', $file));
                //var_dump($translations);
                return  array(ltrim($this->groupName(Str::replaceLast($path, '', $file)), '/') => ltrim($this->groupName(Str::replaceLast($path, '', $file)), '/')." (".$count.")");
            })
            ->flatten();
    }

    public function countEmptyEntries($file){

        $translation = $this->translations($file);
        $group = $this->groupName($file);
        $entries = 0;
        $count = 0;
        foreach ($translation as $key => $value)
        {
            $this->searchForEmpty($key, $value, null, $count, $entries, $group);
        }
        return $entries."/".$count;
    }

    protected function searchForEmpty($key, $value, $prefix, &$count, &$entries, $group)
    {
        $prefix = $prefix ? "{$prefix}.{$key}" : $group.".".$key;
        if (is_array($value))
        {
            foreach ($value as $subKey => $subValue)
            {
                $this->searchForEmpty($subKey, $subValue, $prefix, $count,$entries, $group);
            }
        }
        else
        {
            if(Lang::has($prefix, $this->languageRead, false)){
                $count++;
            }

            if(Lang::has($prefix, 'de', false)){
                $entries ++;
            }

        }
    }

    /**
     * Get default language
     *
     * @return string
     */
    public function defaultLanguage()
    {
        return config('app.fallback_locale', 'de');
    }


    /**
     * Get the group name from a filename
     *
     * @param $filename
     *
     * @return mixed
     */
    public function groupName($filename)
    {
        return preg_replace('/\.php$/', '', $filename);
    }
    /**
     * Get default language
     *
     * @param string $path
     * @param string $language
     *
     * @return string
     */
    protected function namespacePath($path, $language = null)
    {
        return "{$path}{$this->directory_separator}" . ($language ?: $this->defaultLanguage());
    }

    /**
     * List content of a path
     *
     * @param null $path
     * @param bool $recursive
     *
     * @return \Illuminate\Support\Collection
     */
    protected function pathContent($path = null, $recursive = false)
    {

        //var_dump($this->filesystem->listContents($path, $recursive));
        //return new Collection(($this->filesystem->listContents($path, $recursive)));
        return new Collection(File::files($path));
    }

}
