<?php
/**
 * This file contains the QGoogleListFiles class.
 *
 * @author David Maliska
 */

/**
 * Require DocBlock
 */
require_once('QGoogleDrive.class.php');

/**
 * This class download properties from all files on Google Drive
 *
 * @property int $numberOfFiles contains number of received files
 * @property Array List of Google_DriveFile $arrayOfFiles contains array of Google files from Google Drive 
 * @property string $rootFolderID The ID of root folder
 * @property string $quotaTotal Total storage
 * @property string $quotaUsed Used storage
 */
class QGoogleListFiles extends QGoogleDrive {
    ///////////////////////////
    // Private Member Variables
    ///////////////////////////
    
    /** @var int Number of received files */
    protected $numberOfFiles;
    
    /** @var Array List of Google_DriveFile Array of Google files from Google Drive */
    protected $arrayOfFiles;
    
    /** @var string The ID of root folder */
    protected $rootFolderID;
    
    /** @var string Total storage */
    protected $quotaTotal;
    
    /** @var string Used storage */
    protected $quotaUsed;
    
    //////////
    // Methods
    //////////
    /**
     * Create the QGoogleListFiles object.
     *
     * @return void
     */
    public function __construct() {
        parent::__construct();
        
        $this->arrayOfFiles = array();
        $pageToken = NULL;
        do {
            $parameters = array();
            try {
                if ($pageToken) {
                    $parameters['pageToken'] = $pageToken;
                }
                $files = $this->service->files->listFiles($parameters);
                $this->arrayOfFiles = array_merge($this->arrayOfFiles, $files->getItems());
                $pageToken = $files->getNextPageToken();
            } catch (Google_Exception $eG) {
                $this->errorGoogle = $eG->getMessage();
            } catch (Exception $e) {
                $this->error = $e->getMessage(); 
            }
        } while ($pageToken);
        
        try {
            $aboutService = $this->service->about->get();
            $this->rootFolderID = $aboutService->getRootFolderId();
            $this->quotaTotal = $aboutService->getQuotaBytesTotal();
            $this->quotaUsed = $aboutService->getQuotaBytesUsed();
        } catch (Google_Exception $eG) {
            $this->errorGoogle = $eG->getMessage();
        } catch (Exception $e) {
            $this->error = $e->getMessage(); 
        }
    }
    
    /**
     * Retrieve filtred files.
     *
     * @param string  $folder      The name of folder to filtred files (null:all files)
     *
     * @return array|null
     */
    public function retrieveFiltredFiles($folder = null) {
        switch ($folder) {
            case 'trash':
                $trash = "true";
                $shared = "";
                $folderId = "";
                break;
            case 'main':
                $trash = "";
                $shared = "";
                $folderId = $this->rootFolderID;
                break;
            case 'shared':
                $trash = "";
                $shared = "true";
                $folderId = "";
                break;
            
            default:
                $trash = "";
                $shared = "";
                $folderId = "";
                break;
        }
        $arrayFull = array();
        foreach ($this->arrayOfFiles as $file) {
            $arrayColumn = array();
            try {
                $arrayRow = json_encode($file);
                $arrayRow = json_decode($arrayRow, true);
                $tempShared = json_encode($arrayRow["shared"]);
                $tempLabels = json_encode($arrayRow["labels"]);
                $tempLabels = json_decode($tempLabels, true);
                $tempTrashed = json_encode($tempLabels["trashed"], JSON_UNESCAPED_UNICODE);
                $tempMimeType = json_encode($arrayRow["mimeType"], JSON_UNESCAPED_UNICODE);
                $tempMimeType = stripslashes(str_replace('"', '', $tempMimeType));
                $tempParents = json_encode($arrayRow["parents"]);
                $tempParents = json_decode($tempParents, true);
                $tempParents = json_encode($tempParents[0]);
                $tempParents = json_decode($tempParents, true);
                $tempParentID = json_encode($tempParents["id"], JSON_UNESCAPED_UNICODE);
                $tempParentID = stripslashes(str_replace('"', '', $tempParentID));
                if((!$folder || $shared == $tempShared || $trash == $tempTrashed || ($tempTrashed == "false" && $folderId == $tempParentID)) && $tempMimeType != "application/vnd.google-apps.folder") {
                    $tempTitle = json_encode($arrayRow["title"], JSON_UNESCAPED_UNICODE);
                    $tempTitle = stripslashes(str_replace('"', '', $tempTitle));
                    if($tempTitle != "null") {
                        array_push($arrayColumn, $tempTitle);

                        $tempCreatedDate = json_encode($arrayRow["createdDate"], JSON_UNESCAPED_UNICODE);
                        $tempCreatedDate = stripslashes(str_replace('"', '', $tempCreatedDate));
                        $createdDate = new QDateTime($tempCreatedDate);
                        $createdDate->AddHours(2);
                        array_push($arrayColumn, $createdDate->qFormat('hhh:mm D.M.YYYY'));
                        
                        $tempModifiedDate = json_encode($arrayRow["modifiedDate"], JSON_UNESCAPED_UNICODE);
                        $tempModifiedDate = stripslashes(str_replace('"', '', $tempModifiedDate));
                        $modifiedDate = new QDateTime($tempModifiedDate);
                        $modifiedDate->AddHours(2);
                        array_push($arrayColumn, $modifiedDate->qFormat('hhh:mm D.M.YYYY'));

                        $tempDescription = json_encode($arrayRow["description"], JSON_UNESCAPED_UNICODE);
                        $tempDescription = stripslashes(str_replace('"', '', $tempDescription));
                        $tempDescription = str_replace('null', '-', $tempDescription);
                        array_push($arrayColumn, $tempDescription);

                        $tempId = json_encode($arrayRow["id"], JSON_UNESCAPED_UNICODE);
                        $tempId = stripslashes(str_replace('"', '', $tempId));
                        array_push($arrayColumn, $tempId);

                        $tempShared = json_encode($arrayRow["shared"], JSON_UNESCAPED_UNICODE);
                        $tempShared = stripslashes(str_replace('"', '', $tempShared));
                        $tempShared = str_replace('true', QApplication::Translate("Yes"), $tempShared);
                        $tempShared = str_replace('false', QApplication::Translate("No"), $tempShared);
                        array_push($arrayColumn, $tempShared);
                        
                        $tempIconLink = json_encode($arrayRow["iconLink"], JSON_UNESCAPED_UNICODE);
                        $tempIconLink = stripslashes(str_replace('"', '', $tempIconLink));
                        array_push($arrayColumn, $tempIconLink);
                        
                        $tempFileExtension = json_encode($arrayRow["fileExtension"], JSON_UNESCAPED_UNICODE);
                        $tempFileExtension = stripslashes(str_replace('"', '', $tempFileExtension));
                        array_push($arrayColumn, $tempFileExtension);
                        
                        $tempFileSize = json_encode($arrayRow["fileSize"], JSON_UNESCAPED_UNICODE);
                        $tempFileSize = stripslashes(str_replace('"', '', $tempFileSize));
                        array_push($arrayColumn, $tempFileSize);

                        array_push($arrayFull, $arrayColumn);
                    }
                }
            } catch (Google_Exception $eG) {
                $this->errorGoogle = $eG->getMessage();
            } catch (Exception $e) {
                $this->error = $e->getMessage();
            } 
        }
        $this->numberOfFiles = count($arrayFull);
        return $arrayFull;
    }
    
    /////////////////////////
    // Public Properties: GET
    /////////////////////////
    /**
    * PHP Magic __get method implementation.
    * @param string $strName Name of the property to be fetched.
    *
    * @return int|Array List of Google_DriveFile|Google_Client|Google_DriveService|string|null
    * @throws Exception|QCallerException
    */
    public function __get($strName) {
        switch ($strName) {
            case 'NumberOfFiles': return $this->numberOfFiles;
            case 'ArrayOfFiles': return $this->arrayOfFiles;
            case 'RootFolderID': return $this->rootFolderID;
            case 'QuotaTotal': return $this->quotaTotal;
            case 'QuotaUsed': return $this->quotaUsed;
                
            default:
                try {
                    return parent::__get($strName);
                } catch (QCallerException $objExc) {
                    $objExc->IncrementOffset();
                    throw $objExc;
                }
        }
    }
}
?>

