<?php

namespace App\Helpers;

use Illuminate\Support\Facades\DB;

class ValidationHelper
{
    public function albumPathUnique($attribute, $value, $parameters, $validator)
    {
        $data = $validator->getData();
        $parentID = intval($data['parent_album_id']);
        $name = $data['name'];

        if ($parentID === 0)
        {
            $parentID = null;
        }

        $queryParams = [
            ['name', $name],
            ['parent_album_id', $parentID]
        ];

        if (count($parameters) > 0)
        {
            $existingAlbumID = intval($parameters[0]);
            $queryParams[] = ['id', '<>', $existingAlbumID];
        }

        $count = DB::table('albums')->where($queryParams)->count();

        return ($count == 0);
    }

    public function directoryExists($attribute, $value, $parameters, $validator)
    {
        return file_exists($value) && is_dir($value);
    }

    public function isDirectoryEmpty($attribute, $value, $parameters, $validator)
    {
        if (!$this->directoryExists($attribute, $value, $parameters, $validator))
        {
            return false;
        }

        $iterator = new \DirectoryIterator($value);
        $count = 0;

        foreach ($iterator as $item)
        {
            if ($item->isDot())
            {
                continue;
            }

            $count++;
        }

        return ($count == 0);
    }

    public function isPathWriteable($attribute, $value, $parameters, $validator)
    {
        return $this->directoryExists($attribute, $value, $parameters, $validator) && is_writeable($value);
    }
}