<?php

namespace Snaju\Inception\Util;

use Composer\Autoload\ClassLoader;
use Doctrine\Common\Annotations\AnnotationReader;

// TODO: add docs
class AnnotationHelper
{

    public static function getClassAnnotations($className)
    {
        $ref = new \ReflectionClass($className);
        if ($ref instanceof \ReflectionClass) {
            $reader = new AnnotationReader();
            return $reader->getClassAnnotations($ref);
        }
        return [];
    }

    public static function hasClassAnnotation($className, $annotation)
    {
        $ref = new \ReflectionClass($className);
        if ($ref instanceof \ReflectionClass) {
            $reader = new AnnotationReader();
            if ($reader->getClassAnnotation($ref, $annotation) != null) {
                return true;
            }
        }
        return false;
    }

    public static function getClassAnnotation($className, $annotation)
    {
        if ($className instanceof \ReflectionClass) {
            $ref = $className;
        } else {
            $ref = new \ReflectionClass($className);
        }

        if ($ref instanceof \ReflectionClass) {
            $reader = new AnnotationReader();
            $annon = $reader->getClassAnnotation($ref, $annotation);
            if ($annon != null) {
                return $annon;
            }
        }

        return null;
    }

    public static function findClassesWithAnnotation($annotation)
    {
        $a = [];
        foreach (get_declared_classes() as $class) {
            $ref = new \ReflectionClass($class);
            if ($ref instanceof \ReflectionClass) {
                if (self::hasClassAnnotation($ref->getName(), $annotation)) {
                    $a[] = $ref;
                }
            }
        }
        return $a;
    }

    public static function findMethodsWithAnnotation($annotation)
    {

        $reader = new AnnotationReader();

        $a = [];
        foreach (get_declared_classes() as $class) {
            $ref = new \ReflectionClass($class);
            foreach ($ref->getMethods() as $method) {
                if ($reader->getMethodAnnotation($method, $annotation) != null) {
                    $a[] = $method;
                }
            }
        }

        return $a;
    }

    public static function findPropertiesWithAnnotation($annotation)
    {
        $reader = new AnnotationReader();

        $a = [];
        foreach (get_declared_classes() as $class) {
            $ref = new \ReflectionClass($class);
            foreach ($ref->getProperties() as $property) {
                if ($reader->getPropertyAnnotation($property, $annotation) != null) {
                    $a[] = $property;
                }
            }
        }

        return $a;
    }

}