<?php

namespace Sowmedia\Repo\API\v1;

class Endpoint {
    private static $endpoint_url = "http://repo.sowmedia.nl/api/v1/";
    private $license_key;

    function __construct($license_key){
        $this->license_key = $license_key;
    }

    function request($uri, $post_data = array()){
        $response = wp_remote_post(
            $this->get_url($uri),
            array(
                "method" => "POST",
                "body" => $post_data,
                "headers" => array(
                    "Sowmedia-License-Key" => $this->license_key,
                    "Sowmedia-URL" => get_site_url()
                )
            )
        );
        if(is_wp_error($response))
            throw new \Exception($response->get_error_message());
        $response = json_decode($response["body"], true);
        if(!$response)
            throw new \Exception("Invalid response");
        if($response["error"])
            throw new Exception($response["message"], isset($response["error_code"]) ? $response["error_code"] : -1);
        return $response;
    }

    function get_url($uri){
        return self::$endpoint_url . $uri;
    }

    function get_package_info($package_slug){
        $response = $this->request("packages/" . $package_slug);
        return $response["package"];
    }

    function get_version_info($package_slug, $version){
        $response = $this->request("packages/" . $package_slug . "/version/" . $version);
        return $response["version"];
    }

    function get_license_info(){
        $response = $this->request("license");
        return $response["license"];
    }

    function get_download_url($package_slug, $version, $send_license_in_url = false){
        $rel_url = "packages/" . $package_slug . "/download/" . $version;
        if($send_license_in_url){
            $rel_url .= "?" . http_build_query(array(
                "license-key" => $this->license_key,
                "url" => get_site_url()
            ));
        }
        return $this->get_url($rel_url);
    }
}
