<?php

namespace Licenzo\Framework\Http;

class RequestType
{
    const API = 'api';

    const ADMIN = 'admin';

    const AJAX = 'ajax';

    const CRON = 'cron';

    const FRONTEND = 'frontend';

    /**
     * Returns if request is for specific $type.
     *
     * @param string $type admin | ajax | cron | api | frontend
     *
     * @return bool
     */
    public static function is($type)
    {
        switch ($type) {
            case static::ADMIN:
                return is_admin();

            case static::AJAX:
                return \defined('DOING_AJAX') && DOING_AJAX;

            case static::CRON:
                return \defined('DOING_CRON') && DOING_CRON;

            case static::API:
                return \defined('REST_REQUEST') && REST_REQUEST;

            case static::FRONTEND:
                return (!is_admin() || \defined('DOING_AJAX')) && !\defined('DOING_CRON');


            default:
                return false;
        }
    }

    public static function type()
    {
        if (static::is(static::ADMIN)) {
            return static::ADMIN;
        }

        if (static::is(static::AJAX)) {
            return static::AJAX;
        }

        if (static::is(static::CRON)) {
            return static::CRON;
        }

        if (static::is(static::API)) {
            return static::API;
        }

        if (static::is(static::FRONTEND)) {
            return static::FRONTEND;
        }

        return null;
    }

    public static function isApi()
    {
        return static::is(static::API);
    }

    public static function isAjax()
    {
        return static::is(static::AJAX);
    }

    public static function isCron()
    {
        return static::is(static::CRON);
    }

    public static function isAdmin()
    {
        return static::is(static::ADMIN);
    }

    public static function isFrontend()
    {
        return static::is(static::FRONTEND);
    }
}
