<?php

namespace App\Helpers\FirstParty\DFS;

use Exception;
use Http;

class DFSCommon
{
    public static function getTaskResult($task)
    {
        $task_object = new DFSResponse($task);

        return (object) [
            'type' => 'task',
            'path' => implode('/', $task_object->getPath()),
            'id' => $task_object->getId(),
            'is_successful' => $task_object->isSuccessful(),
            'result' => $task_object->getResult(),
            'message' => $task_object->getStatusMessage(),
        ];

    }

    public static function getTasks($response)
    {

        $dfs_object = new DFSResponse($response);

        if ($dfs_object->isSuccessful()) {
            return $dfs_object->getTasks();
        }

        return [];
    }

    public static function getTask($response, $key)
    {
        $tasks = self::getTasks($response);

        if (count($tasks) > 0) {
            if (isset($tasks[$key])) {
                $task_object = $tasks[$key];

                if (count($tasks) > 1) {
                    $task_object->client_message = 'There are '.count($tasks).' tasks.';
                }

                return $task_object;
            }
        }

        return null;
    }

    public static function apiCall($method, $action_url, $query)
    {

        $api_url = self::getApiUrl();

        $api_version = config('dataforseo.api_version');

        $api_timeout = config('dataforseo.timeout');

        $full_api_url = "{$api_url}{$api_version}{$action_url}";

        dump($full_api_url);
        dump($query);

        $http_object = Http::timeout($api_timeout)->withBasicAuth(config('dataforseo.login'), config('dataforseo.password'));

        if (strtoupper($method) == 'GET') {
            try {
                $response = $http_object->withUrlParameters(
                    json_encode([(object) $query])
                )->get('');

            } catch (Exception $e) {
                return self::defaultFailedResponse($e);
            }

        } elseif (strtoupper($method) == 'POST') {
            try {
                $response = $http_object->withBody(
                    json_encode([(object) $query])
                )->post("{$api_url}{$api_version}{$action_url}");
            } catch (Exception $e) {
                return self::defaultFailedResponse($e);
            }
        } else {
            throw new Exception('Invalid action method parameter.');
        }

        if ($response->successful()) {
            return json_decode($response->body(), false);
        }

        return self::defaultFailedResponse();

    }

    public static function getApiUrl()
    {
        $api_url = config('dataforseo.url');

        if (config('dataforseo.sandbox_mode')) {
            $api_url = config('dataforseo.sandbox_url');
        }

        return $api_url;
    }

    private static function defaultFailedResponse(Exception $e = null)
    {
        $message = 'No such url.';

        if (! is_null($e)) {
            $message = $e->getMessage();
        }

        return (object) [
            'version' => '-1',
            'status_code' => -1,
            'status_message' => $message,
            'time' => '0 sec.',
            'cost' => 0,
            'tasks_count' => 0,
            'tasks_error' => 0,
            'tasks' => [],
        ];
    }
}
