<?php

class VersionApi extends Api
{
    public $apiName = 'version';

    public function __construct($requestUri, $encryption=true) {
        $this->requestWhitelist['createAction'] = 1;
        parent::__construct($requestUri, $encryption);
    }
    
    public function indexAction()
    {
        return $this->response(
            array(
                'error' => 'Data not found'
            ), 404);
    }

    /**
     * Method GET
     * Get single record (by id)
     * http://DOMAIN/address/1
     * @return string
     */
    public function viewAction()
    {
        return $this->response(
            array(
                'error'=> 'Data not found'
            ), 404);
    }

    public function createAction()
    {
        syslog(LOG_WARNING,"VersionApi::createAction()");
        $message = "Version data not found";

        $platform = $this->requestParams["platform"] ?? "";
        $rev_count = $this->requestParams["rev_count"] ?? "";
        $short_hash = $this->requestParams["short_hash"] ?? "";

        try {
            $db = new Db();
            $current = Version::getAppVersion($db->getConnect(), $platform, $rev_count, $short_hash);
            $newer = Version::getNewAppVersion($db->getConnect(), $platform, $rev_count, $short_hash);
            if ((!is_array($current) || !array_key_exists("id",$current)) 
             && (!is_array($newer) || !array_key_exists("id",$newer))) {
                syslog(LOG_WARNING,'Invalid platform and/or revision and/or hash');
                throw new Exception('Invalid platform and/or revision and/or hash');
            }
            return $this->response([
                "current" => $current,
                "newer" => $newer
            ],200);
        } catch (Exception $e) {
            $message = $e->getMessage();
        } 
        return $this->response(
            array(
                "error" => $message
            ), 404);
    }

    public function updateAction()
    {
        return $this->response(
            array(
                "error" => "Update error"
            ), 400);
    }

    public function deleteAction()
    {
        return $this->response(
            array(
                "error" => "Delete error"
            ), 500);
    }
}
