<?php

	define('APS_DEVELOPMENT_MODE', true);
	require "aps/2/runtime.php";	

	/**
	* @type("http://aps-standard.org/samples/github/app/2.0")
	* @implements("http://aps-standard.org/types/core/application/1.0","http://odin.com/init-wizard/config/1.0","http://odin.com/init-wizard-vendor-catalog/config/1.0")
	*/
	class app extends \APS\ResourceBase
	{
        /**
         * @link("http://aps-standard.org/samples/github/tenant/2.0[]")
         */
        public $tenants;

        /**
         * @link("http://aps-standard.org/samples/github/license/2.0[]")
         */
        public $licenses;

        /**
         * @link("http://aps-standard.org/samples/github/reseller/2.0[]")
         */
        public $resellers;

        /**
         * @type(string)
         * @title("BaseURL")
         * @required
         * @description("Base endpoint in the external system. Note: The final slash is required.")
         */
        public $baseURL = "https://api.github.com/";

        /**
         * @verb(GET)
         * @path("/getInitWizardConfig")
         * @access(admin, true)
         * @access(owner, true)
         * @access(referrer, true)
         */
        public function getInitWizardConfig()
        {
            $myfile = fopen("./wizard_data.json", "r") or die("Unable to open file!");
            $data = fread($myfile,filesize("./wizard_data.json"));
            fclose($myfile);
            return json_decode($data);
        }

        /**
         * @verb(POST)
         * @path("/fetchCatalog")
         * @param("http://odin.com/init-wizard-vendor-catalog/config/1.0#FetchCatalogRequest",body)
         * @access(admin, true)
         * @access(owner, true)
         * @access(referrer, true)
         */
        public function fetchCatalog($request)
        {
            $logger = \APS\LoggerRegistry::get(); // Used for troubleshooting
            $logger->info("\nFETCH-CATALOG: Entered the function with request: ");
            if($request->apsType != "http://aps-standard.org/samples/github/license/2.0" ||
                    count($request->offerMpns) == 0)
                throw new \Exception("Incorrect APS type, the 'http://aps-standard.org/samples/github/license/2.0' is expected");

            $jsondata = file_get_contents("./fetch_catalog_template.json");
            $tmpl = json_decode($jsondata);

            $apsResources = [];
            $resourceTypes = [];
            $servicePlans = [];

            foreach ($request->offerMpns as $mpn) {
                $reposArr = explode('-', explode('/', $mpn->mpn)[1]);
                $reposStr = implode(', ', $reposArr);

                $apsResource = clone $tmpl->apsResource;
                $resourceType = clone $tmpl->resourceType;
                $servicePlan = clone $tmpl->servicePlan;

                # Setting a apsResource:
                $apsResource->id = 'idc'.(string)rand(1000000000000, 9999999999999);
                $apsResource->fields = new stdClass();
                $apsResource->fields->profileName = sprintf("Access with scopes: %s", $reposStr);
                $apsResource->fields->name = sprintf("Scopes: %s", $reposStr);
                $apsResource->fields->scopes = [];
                foreach ($reposArr as $repo) {
                    array_push($apsResource->fields->scopes, $repo);
                }
                $apsResource->fields->mpn = $mpn->mpn;

                # Setting a resourceType:
                $resourceType->name = sprintf($resourceType->name, $reposStr);
                $resourceType->id = rand(-599999, -500000);
                $resourceType->actParams = new stdClass();
                $resourceType->actParams->resource_uid = $apsResource->id;

                # Setting a servicePlan:
                $servicePlan->name = sprintf($servicePlan->name, $reposStr);
                $servicePlan->id = rand(-999, -100);
                $servicePlan->shortDescription = sprintf($servicePlan->shortDescription, $reposStr);
                $servicePlan->longDescription = sprintf($servicePlan->longDescription, $reposStr);
                $servicePlan->resources = [(object)[
                    'id' => rand(-799999, -700000),
                    'rtID' => $resourceType->id,
                    'incl' => 0,
                    'min' => 1,
                    'max' => -1
                ]];

                # Push the generated objects to the response arrays:
                array_push($apsResources, clone $apsResource);
                array_push($resourceTypes, $resourceType);
                array_push($servicePlans, $servicePlan);
            }

            # Response:
            $response = new stdClass();
            $response->apsResources = $apsResources;
            $response->resourceTypes = $resourceTypes;
            $response->servicePlans = $servicePlans;

            return $response;
        }

        /**
         * @verb(GET)
         * @path("/testConnection")
         * @param(object,body)
         * @access(admin, true)
         * @access(owner, true)
         * @access(referrer, true)
         */
        public function testConnection($body)
        {
            return "";
        }

    }
?>
