<?php
defined('ABSPATH') || exit;

if (!class_exists('Aimogen_Response')) {

class Aimogen_Response {

    private $ok;
    private $value;
    private $error;
    private $meta;

    public function __construct($ok, $value = null, $error = '', $meta = array()) {
        $this->ok    = (bool) $ok;
        $this->value = $value;
        $this->error = $error;
        $this->meta  = is_array($meta) ? $meta : array();
    }

    public function ok() {
        return $this->ok;
    }

    public function failed() {
        return !$this->ok;
    }

    public function text() {
        if (!$this->ok) {
            return '';
        }

        if (is_string($this->value)) {
            return $this->value;
        }

        return wp_json_encode($this->value);
    }

    public function data() {
        if (!$this->ok) {
            return array();
        }

        if (is_array($this->value)) {
            return $this->value;
        }

        if (is_string($this->value)) {
            $json = json_decode($this->value, true);

            if (json_last_error() === JSON_ERROR_NONE) {
                return $json;
            }
        }

        return array();
    }

    public function url() {
        if (!$this->ok) {
            return '';
        }

        if (is_string($this->value)) {
            return $this->value;
        }

        if (is_array($this->value) && isset($this->value['url'])) {
            return $this->value['url'];
        }

        return '';
    }

    public function raw() {
        return $this->value;
    }

    public function error() {
        return $this->error;
    }

    public function meta($key = null) {
        if ($key === null) {
            return $this->meta;
        }

        return isset($this->meta[$key]) ? $this->meta[$key] : null;
    }

    public function __toString() {
        return $this->text();
    }
}

}