<?php
namespace OfficeBrain\Bundle\CmsBundle\Manager\Extended;

use OfficeBrain\Bundle\CmsBundle\Manager\AbstractManager\CmsMediaLibraryAbstract as CmsMediaLibraryAbstract;

//use OfficeBrain\Bundle\CmsBundle\Entity\CmsPageMaster;
//use OfficeBrain\Bundle\CmsBundle\Entity\CmsPageLanguage;

class CmsMediaLibraryExtended extends CmsMediaLibraryAbstract
{
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to set member variables default value
     *
     * @param 1: $entityManager
     * @param 2: $request
     * @param 3: $knpPaginator
     * @param 4: $mediaFileUrl
     * @param 5: $mediaFilePath
     *
     * @return: NULL
     *
     * @throws Exception: Null
     */
    public function __construct($entityManager, $request, $knpPaginator, $mediaFileUrl, $mediaFilePath)
    {
        parent::__construct($entityManager, $request, $knpPaginator, $mediaFileUrl, $mediaFilePath);
    }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to unset member variables
     *
     * @param : None
     *
     * @return NULL
     *
     * @throws Exception: Null
     */
    public function __destruct()
    {
        parent::__destruct();
    }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to validate the uploaded file and move it to the targeted directory
     *
     * @param : $formData
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function uploadMediaFile($file)
    {
        if (is_array($file)) {
            foreach ($file as $fileOBject) {
                $result[] = $this->moveFile($fileOBject);
            }
        } else {
            $result[] = $this->moveFile($file);
        }
        unset($file);
        return $result;
    }
     /**
     * @author Employee Id: 4471
     *
     * Description : This function is used to validate the uploaded file and uploaded to targeted directory
     *
     * @param : $formData
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    
     public function uploadMediaFileToFolder($file, $folderPath, $addtoDb)
     {
         if (!file_exists($folderPath)) {
             mkdir($folderPath, 0777, true);
         }
         if (is_array($file)) {
             foreach ($file as $fileOBject) {
                 $result[] = $this->moveFile($fileOBject, $folderPath, $addtoDb);
             }
         } else {
             $result[] = $this->moveFile($file, $folderPath, $addtoDb);
         }
         unset($file);
         return $result;
     }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to validate the uploaded file and move it to the targeted directory
     *
     * @param : $formData
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function moveFile($file, $folderPath='', $addtoDb='yes')
    {
        $error = '';
        $status = $this->createMediaFileDirectory();
        if (isset($status['error'])) {
            $error = $status['error'];
        }
        
        $fileType = $this->checkUploadedMediaType($file);
        if (!$fileType) {
            //$error = "MEDIA_FILE_TYPE_NOT_ALLOWED";
        	$fileType = end(explode('.', $file['name']));
        }
        
        $fileSize = $this->checkUploadedMediaSize($file);
        if (!$fileSize) {
            $error = "MEDIA_FILE_TOO_LARGE";
        }
        
        if (empty($error)) {
            $fileName = $this->getNewFileNameIfFileExists($file['name']);
            if ($folderPath!='') {
                $targetDir = $folderPath.'/'.$fileName;
            } else {
                $targetDir = $this->mediaFilePath.'/'.$fileName;
            }
            move_uploaded_file($file['tmp_name'], $targetDir);
            //$uploadedMediaInfo = array('name' => $fileName, 'path' => $targetDir, 'type' => $fileType);
            $uploadedMediaInfo = array('name' => $fileName, 'type' => $fileType);
            if ($addtoDb=='yes') {
                $result = $this->setMedia($uploadedMediaInfo);
                if (isset($result['error'])) {
                    $error = $result['error'];
                }
            }
            
            //unset($fileName);
            unset($targetDir);
            unset($uploadedMediaInfo);
            unset($result);
        }
        
        unset($file);
        unset($fileType);
        unset($fileSize);
        
        if (!empty($error)) {
            return array('error' => $error);
        }
        
        unset($error);
        return $fileName;
    }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to store the uploaded media's data into database
     *
     * @param : $uploadedMediaInfo
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function setMedia($uploadedMediaInfo)
    {
        $result = $this->cmsMediaLibraryRepository->setMediaLibrary($uploadedMediaInfo);
        if (empty($result)) {
            unset($result);
            return array('error' => 'unable to upload file');
        } else {
            unset($result);
            return array('success' => 'file uploaded successfully');
        }
    }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to check the upload file's type
     *
     * @param : $file object
     *
     * @return type of the file
     *
     * @throws Exception : Null
     *
     **/
    public function checkUploadedMediaType($file)
    {
        if (is_array($file)) {
            if (isset($file['type'])) {
                if (in_array($file['type'], $this->cmsMediaAllowedImages)) {
                    $mediaType = "Image";
                } elseif (in_array($file['type'], $this->cmsMediaAllowedDocuments)) {
                    $mediaType = "Document";
                } elseif (in_array($file['type'], $this->cmsMediaAllowedPdf)) {
                    $mediaType = "PDF";
                } else {
                    $mediaType = null;
                }
            }/* elseif (function_exists('finfo_open')){
                $finfo = finfo_open(FILEINFO_MIME);
                $mimetype = finfo_file($finfo, $file['tmp_name']);
            } */
        } elseif (is_object($file)) {
            if ($file->getClientmimeType()) {
                if (in_array($file->getClientmimeType(), $this->cmsMediaAllowedImages)) {
                    $mediaType = "Image";
                } elseif (in_array($file->getClientmimeType(), $this->cmsMediaAllowedDocuments)) {
                    $mediaType = "Document";
                } elseif (in_array($file->getClientmimeType(), $this->cmsMediaAllowedPdf)) {
                    $mediaType = "PDF";
                } else {
                    $mediaType = null;
                }
            }/* elseif (function_exists('finfo_open')){
            $finfo = finfo_open(FILEINFO_MIME);
            $mimetype = finfo_file($finfo, $file['tmp_name']);
            } */
        }
        unset($file);
        return $mediaType;
    }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to check the size of the uploaded file
     *
     * @param : $file object
     *
     * @return boolean
     *
     * @throws Exception : Null
     *
     **/
    public function checkUploadedMediaSize($file)
    {
        $status = null;
        if (is_array($file)) {
            if ($file['size'] > $this->cmsConfigurations['option']['cms_media_max_file_size']['status'] * 1024 * 1024) {
                $status  = false;
            } else {
                $status = true;
            }
        } elseif (is_object($file)) {
            if ($file->getClientSize() > $this->cmsConfigurations['option']['cms_media_max_file_size']['status'] * 1024 * 1024) {
                $status = false;
            } else {
                $status = true;
            }
        }
        
        unset($file);
        return $status;
    }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to fetch the uploaded media from database
     *
     * @param : Null
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function getMedia()
    {
        $keyword = $this->request->get('keywords');
        $mediaType= $this->request->get('mediatype');
        if (empty($mediaType)) {
            $mediaType = $this->cmsMediaDefaultTab;
        }
        $mediaLibraryList = $this->cmsMediaLibraryRepository->getMediaLibrary($mediaType, $keyword);
        /* $mediaTypes = $this->cmsMediaLibraryRepository->getMediaType();
        if (!empty($mediaTypes)) {
            foreach ($mediaTypes as $index) {
                foreach ($index as $key => $type) {
                    $temp[] = $type;
                }
            }
            $mediaTypes = $temp;
        } */
        
        unset($keyword);
        unset($mediaType);
        
        if (!empty($mediaLibraryList)) {
            //return array($mediaTypes, $this->knpPaginator->paginate($mediaLibraryList, $this->request->get('page', '1'), $this->recordsPerPage, array(), count($mediaLibraryList)));
            return $this->knpPaginator->paginate($mediaLibraryList, $this->request->get('page', '1'), $this->recordsPerPage, array(), count($mediaLibraryList));
        }
    }
    
    
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to download a file
     *
     * @param : $name
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function downloadMedia($name)
    {
        if (file_exists($this->mediaFilePath.'/'.$name)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($this->mediaFilePath.'/'.$name));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($this->mediaFilePath.'/'.$name));
            readfile($this->mediaFilePath.'/'.$name);
            unset($name);
            exit;
        } else {
            unset($name);
        }
    }
    
    
    
     /**
     * @author Employee Id: 4471
     *
     * Description : This function is used to copy file from one folder to another
     *
     * @param : $fromFolderPath, $toFolderPath ,$originalImageName , $duplicateImageName
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function copyMedia($fromFolderPath, $toFolderPath, $originalImageName, $duplicateImageName='')
    {
        $toFolderName = substr(strrchr(rtrim($toFolderPath, '/'), '/'), 1);
        
         //Check existance file to copy
        //if(!$this->exists($fromFolderPath, $originalImageName))
        //    throw new Exception(sprint("Can't copy unexisting file \"%s\"", $originalImageName));
        
        if (!file_exists($toFolderPath)|| !is_dir($toFolderPath)) {
            $ret=mkdir($toFolderPath, 0777, true);
             //if(!$ret)
               // throw new Exception(sprintf('Could not create directory "%s".', $toFolderPath));
        }
        
        $currentDateTime = new \DateTime();
        
        chmod($fromFolderPath, 0777);
        //chmod($toFolderPath, 0777);
        if ($duplicateImageName!='') {
        	$fileName = $duplicateImageName;
        } else {
        	$fileName = $currentDateTime->format('YmdHis').'_'.$originalImageName;
        }
        
        $fileName = str_replace(" ","-",$fileName);
        copy($fromFolderPath.'/'.$originalImageName, $toFolderPath.'/'.$fileName);
        
        return $fileName;
    }

    /**
     * @author Employee Id: 4471
     *
     * To delete exist file
     *
     * @param string $filePath
     * @param string $fileName
     *
     * @throws Exception
     *
     * @return boolean
     */
    public function deleteFile($filePath, $fileName)
    {
        
        //if(!$this->exists($filePath, $fileName))
            //throw new Exception(sprint("Can't delete unexisting file \"%s\"", $fileName));
    
        return unlink($filePath .'/'. $fileName);
    }

    /**
     * @author Employee Id: 4471
     * Checks if the specified file exists in the specified folder type
     *
     * @param $filePath
     * @param $fileName
     *
     * @return bool
     */
    public function exists($filePath, $fileName)
    {
        return file_exists($filePath . $fileName);
    }


    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to delete a file using file name
     *
     * @param : $name
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function deleteMediaByName($name)
    {
        /* if (file_exists($this->mediaFilePath.'/'.$name)) {
            $fileData = $this->cmsMediaLibraryRepository->deleteMedia($name);
            unlink($this->mediaFilePath.'/'.$name);
            unset($name);
            return true;
        } else {
            unset($name);
            return false;
        } */
        $fileData = $this->cmsMediaLibraryRepository->deleteMediaByName($name);
        return true;
    }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to delete a file using file id
     *
     * @param : $id
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function deleteMediaById($id)
    {
        $fileData = $this->cmsMediaLibraryRepository->deleteMediaById($id);
        return true;
    }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to view the image
     *
     * @param : Null
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function getImage()
    {
        $imageName = $this->cmsMediaLibraryRepository->getImage($this->request->get('name'));
        if (empty($imageName)) {
            $imageName = "No Image found";
        }
        return array($this->mediaFileUrl, $imageName);
    }
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to view the image
     *
     * @param : Null
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function getMediaLibraryRecords($mediaType = null)
    {
        $mediaLibraryList = $this->cmsMediaLibraryRepository->getMediaLibraryRecords($mediaType);
        $mediaTypes = $this->cmsMediaLibraryRepository->getMediaType();
        if (empty($mediaLibraryList)) {
            $returnData = array("media_types" => null, "media_library_records" => null);
        } else {
            $returnData = array("media_types" => $mediaTypes, "media_library_records" => $mediaLibraryList);
        }
        unset($mediaLibraryList);
        unset($mediaTypes);
        return $returnData;
    }
    
    
    /**
     * @author Employee Id: 4471
     *
     * Description : This function is used to view the image with pagination
     *
     * @param : Null
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function getMediaLibraryRecordsWithPagination($mediaType = null,$page=1,$noOfRecord=2)
    {
    	$mediaLibraryList = $this->cmsMediaLibraryRepository->getMediaLibraryRecordsWithPagination($mediaType,$page,$noOfRecord);
    	$mediaTypes = $this->cmsMediaLibraryRepository->getMediaType();
    	if (empty($mediaLibraryList)) {
    		$returnData = array("media_types" => null, "media_library_records" => null);
    	} else {
    		$returnData = array("media_types" => $mediaTypes, "media_library_records" => $mediaLibraryList);
    	}
    	unset($mediaLibraryList);
    	unset($mediaTypes);
    	return $returnData;
    }
    
    
    /**
     * @author Employee Id: 4464
     *
     * Description : This function is used to validate the uploaded file and move it to the targeted directory
     *
     * @param : $formData
     *
     * @return Null
     *
     * @throws Exception : Null
     *
     **/
    public function uploadMediaFileFront($formData)
    {
        $error = array();
        $status = $this->createMediaFileDirectory();
        if (isset($status['error'])) {
            $error[] = $status['error'];
        }
        $imageName = $formData['image_name'];
        $customerName = $formData['customer_name'];
        $file = $formData['file_object'];
        
        $fileType = $this->checkUploadedMediaType($file);
        if (!$fileType) {
            $error[] = "MEDIA_FILE_TYPE_NOT_ALLOWED";
        }
        
        $fileSize = $this->checkUploadedMediaSize($file);
        if (!$fileSize) {
            $error[] = "MEDIA_FILE_TOO_LARGE";
        }
        
        if (empty($error)) {
            $fileName = $this->getNewFileNameIfFileExists($file->getClientOriginalName());
            $targetDir = $this->mediaFileUrl.'/'.$fileName;
            //echo $this->mediaFilePath.'/'.$fileName;die;
            $file = $file->move($this->mediaFilePath, $fileName);
            
            //$uploadedMediaInfo = array('name' => $fileName, 'path' => $targetDir, 'type' => $fileType, 'image_name' => $imageName, 'customer_name' => $customerName);
            $uploadedMediaInfo = array('name' => $fileName, 'type' => $fileType, 'image_name' => $imageName, 'customer_name' => $customerName);
            $result = $this->setMedia($uploadedMediaInfo);
            if (isset($result['error'])) {
                $error[] = $result['error'];
            }
            unset($result);
        }
        
        unset($file);
        unset($fileType);
        unset($fileSize);
        
        if (!empty($error)) {
            return array('error' => $error);
        }
        
        unset($error);
    }
}
