<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/

/**
 * Class TB_Server_Core_Response
 *
 * General response structure
 * {
 *   'code' => (int)
 *   'data' => (array) optional
 *   'notes' => (array) optional
 * }
 */
class TB_Server_Core_Response extends Francis_Response_Json {

    // Return codes
    const CODE_OK = 200;
    const CODE_NOT_LOGGED_IN = 401;
    const CODE_INVALID_CALL = 404;
    const CODE_INVALID_DATA = 409;
    const CODE_GENERAL_ERROR = 500;
    const CODE_OUTDATED_VERSION = 899;

    protected $code;
    protected $data;
    protected $notes;

    public function __construct( $code = self::CODE_OK,
                                 array $data = array(),
                                 array $notes = array() ) {
        $this->code = $code;
        $this->data = $data;
        $this->notes= $notes;
    }

    public static function getValidCodes() {
        return array(
            self::CODE_OK,
            self::CODE_NOT_LOGGED_IN,
            self::CODE_INVALID_CALL,
            self::CODE_INVALID_DATA,
            self::CODE_GENERAL_ERROR,
            self::CODE_OUTDATED_VERSION
        );
    }

    public function setCode( $code ) {
        if ( in_array( $code, self::getValidCodes() ) ) {
            $this->code = $code;
        }
    }

    public function addData( $key, $value ) {
        $v = $value;
        if ( ( $value instanceof Francis_Db_Row ) ) {
            $v = $value->asArray();
        } else if( is_array( $value ) && 0 < count( $value ) && isset( $value[0] ) && ( $value[0] instanceof Francis_Db_Row ) ) {
            $v = array();
            /** @var Francis_Db_Row $dbRow */
            foreach( $value as $dbRow ) {
                array_push( $v, $dbRow->asArray() );
            }
        }
        $this->data[ $key ] = $v;
    }

    public function addRowsToData( $key, array $rows ) {
        $rowsAsArray = array();
        /** @var Francis_Db_Row $dbRow */
        foreach( $rows as $dbRow ) {
            array_push( $rowsAsArray, $dbRow->asArray() );
        }
        $this->data[ $key ] = $rowsAsArray;
    }

    public function addRowToData( Francis_Db_Row $dbrow, $key = NULL ) {
        if ( is_null( $key ) ) {
            $key = $dbrow->getTable() . '_' . $dbrow->id;
        }
        $this->addData( $key, $dbrow );
    }

    public function addNotification( TB_Server_Utils_Notification $notification ) {
        array_push( $this->notes, $notification );
    }

    public function get() {
        $this->res[ 'code' ] = $this->code;
        if ( is_array( $this->notes ) && 0 < count( $this->notes ) ) {
            $this->res[ 'notes' ] = $this->notes;
        }
        if ( !is_null( $this->data) ) {
            $this->res[ 'data' ] = $this->data;
        }

        return parent::get();
    }
} 