<?php


namespace Magetop\Advancepreview\Controller\Adminhtml\ProductPreview;


use Magento\Backend\App\Action;

/**
 * Class UploadMedia
 * @package Magetop\Advancepreview\Controller\Adminhtml\ProductPreview
 */
class UploadMedia extends \Magetop\Advancepreview\Controller\Adminhtml\ProductPreview
{
    /**
     *
     */
    const CUSTOM_PREVIEWS = 'custom_previews';
    /**
     * @var \Magento\Framework\Filesystem\Driver\File
     */
    protected $file;
    /**
     * @var \Magetop\Advancepreview\Model\AdvancePreviewFileFactory
     */
    protected $advancePreviewFileFactory;
    /**
     * @var \Magetop\Advancepreview\Model\AdvancePreviewUploadFactory
     */
    protected $advancePreviewUploadFactory;
    /**
     * @var \Magetop\Advancepreview\Model\PreviewThreeFactory
     */
    protected $previewThreeFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewThreeFactory
     */
    protected $resPreviewThreeFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory
     */
    protected $colPreviewThreeFactory;

    /**
     * UploadMedia constructor.
     * @param Action\Context $context
     * @param \Magento\Framework\Controller\Result\JsonFactory $jsonFactory
     * @param \Magento\Framework\Filesystem\Driver\File $file
     * @param \Magetop\Advancepreview\Model\AdvancePreviewFileFactory $advancePreviewFileFactory
     * @param \Magetop\Advancepreview\Model\AdvancePreviewUploadFactory $advancePreviewUploadFactory
     * @param \Magetop\Advancepreview\Model\PreviewThreeFactory $previewThreeFactory
     * @param \Magetop\Advancepreview\Model\ResourceModel\PreviewThreeFactory $resPreviewThreeFactory
     * @param \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory $colPreviewThreeFactory
     */
    public function __construct(
        Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
        \Magento\Framework\Filesystem\Driver\File $file,
        \Magetop\Advancepreview\Model\AdvancePreviewFileFactory $advancePreviewFileFactory,
        \Magetop\Advancepreview\Model\AdvancePreviewUploadFactory $advancePreviewUploadFactory,
        \Magetop\Advancepreview\Model\PreviewThreeFactory $previewThreeFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewThreeFactory $resPreviewThreeFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory $colPreviewThreeFactory
    )
    {
        parent::__construct($context, $jsonFactory);
        $this->file = $file;
        $this->advancePreviewFileFactory = $advancePreviewFileFactory;
        $this->advancePreviewUploadFactory = $advancePreviewUploadFactory;
        $this->previewThreeFactory = $previewThreeFactory;
        $this->resPreviewThreeFactory = $resPreviewThreeFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;

    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface|void
     * @throws \Magento\Framework\Exception\FileSystemException
     */
    function execute()
    {
        $response = [
            'status'=>'error',
            'message'=>'Something wrong when adding 3d model',
            'html'=>''
        ];
        $params = $this->getRequest()->getParams();
        $productId = isset($params['product_id']) ? (int)$params['product_id'] : 0;
        $previewId = isset($params['threed_id']) ? (int)$params['threed_id'] : 0;
        $isDefault = isset($params['is_default']) ? (int)$params['is_default'] : 2;
        $title = isset($params['title']) ? trim($params['title']) : '';
        $folderPreview = isset($params['folder_preview']) ? trim($params['folder_preview']) : 0;
        $light = isset($params['preview_light']) ? (int)($params['preview_light']) : 0;
        $zoom = isset($params['preview_zoom']) ? (int)($params['preview_zoom']) : 0;
        $position = isset($params['position']) ? (int)($params['position']) : 0;
        if($title == '' || $folderPreview == '') {
            $response['message'] = 'Please enter all require information';
            return $this->getAjaxResponse($response);
        }

        $customFolder = self::CUSTOM_PREVIEWS.'/product_id_'.$productId;
        $advancePreviewFile = $this->advancePreviewFileFactory->create();
        $customFolderUpload = $advancePreviewFile->getBaseDir($customFolder);
        $uploadModel = $this->advancePreviewUploadFactory->create();
        $media = $advancePreviewFile->getAdvanceMediaFolder();
        if(!$this->file->isExists($customFolderUpload)) {
            $this->file->createDirectory($customFolderUpload,0775);
        }
        $options['file_name'] = 'model-'.$folderPreview.'.zip';
        $options['allow_type'] = ['zip'];
        $customPreview = $uploadModel->uploadFileAndGetName('preview_media',$customFolderUpload,$media.$customFolder,$params, $options);
        if($customPreview == '' && $previewId <= 0) {
            $response['message'] = 'Something wrong when upload 3d model';
            return $this->getAjaxResponse($response);
        }
        $dataSave = array(
            'product_id'=>$productId,
            'title'=>$title,
            'filename'=>$customPreview,
            'folder_preview'=>$folderPreview,
            'is_default'=>$isDefault,
            'preview_light'=>$light,
            'preview_zoom'=>$zoom,
            'position'=>$position,
            'created_at'=>date('Y-m-d H:i:s')
        );
        if($previewId > 0) {
            $dataSave['threed_id'] = $previewId;
            unset($dataSave['created_at']);
        }
        if($previewId > 0 && $customPreview == '') {
            unset($dataSave['filename']);
        }
        if($customPreview != '') {

            $zip = new \ZipArchive();
            $zipFileName = 'model-'.$folderPreview.'.zip';
            $subFolderZip = 'model-'.$folderPreview.'/';
            $pathZip = $customFolderUpload. '/';
            $this->unzipModelPreview($pathZip, $subFolderZip, $zipFileName);
//            $response['message'] .= ' '. $unzipMessage;

            if($this->file->isExists($pathZip.$subFolderZip)) {

                foreach(glob($pathZip.$subFolderZip.'*.*') as $filename){
//                    echo $filename;
                    if($filename != '') {
                        $arFilename = explode('/',$filename);
                        $last = count($arFilename) -1;
                        $filename = $arFilename[$last];
                        $exts = explode('.',$filename);
                        $lastExt =  count($exts) -1;
                        $ext = $exts[$lastExt];
                        if($ext == 'gltf') {
                            $dataSave['file_preview'] = $filename;
                        }
                        elseif($ext == 'png' || $ext == 'jpeg' || $ext == 'jpg') {
                            $dataSave['texture'] = $filename;
                            // save size of Texture to resize when custom  upload
                            list($widthTexture, $heightTexture, $typeTexture, $attrTexture) = getimagesize($pathZip.$subFolderZip.$filename);
                            $dataSave['texture_width'] = $widthTexture;
                            $dataSave['texture_height'] = $heightTexture;

                        }
                    }
                }
            }
            // upload file thumbail
//            $options['file_name'] = 'thumbnail_'.$position.'.zip';

        }
        if($customPreview != '' || $previewId > 0) {
            $options2['allow_type'] = ['jpg','jpeg','png'];
            $thumbnail = $uploadModel->uploadFileAndGetName('thumbnail',$customFolderUpload.'/model-thum-'.$folderPreview,'',$params, $options2);
            if($thumbnail != '') {
                $dataSave['thumbnail'] = $thumbnail;
            }
        }
//        $response['test_a'] = $customFolderUpload. $media.$customFolder.'/model-'.$position;
        $isSave = $this->saveThreeModel($dataSave);
        if($isSave) {
            $response['message'] = 'You have added 3d model success';
            // if save success, unzip file

            $response['status'] = 'success';

            $response['html'] = $this->_view->getLayout()->createBlock('Magetop\Advancepreview\Block\Adminhtml\Product\Edit\Form')->setTemplate('Magetop_Advancepreview::product/items.phtml')->toHtml();

        }
        return $this->getAjaxResponse($response);
    }
    protected function unzipModelPreview($pathZip, $subFolderZip, $fileName) {
        $message = 'Can not unzip';
        try {
            $zip = new \ZipArchive();
            $res = $zip->open($pathZip.$fileName);
            if ($res === TRUE) {
                $zip->extractTo($pathZip.$subFolderZip);
                $zip->close();
                $message = 'Unzip success';
            }
            else {
                $message = 'Unzip xit';
            }
        }
        catch (\Exception $exception) {
            $message = $exception->getMessage();
        }
        return $message;
    }

    /**
     * @param array $dataSave
     * @return bool
     */
    protected function saveThreeModel($dataSave = []) {
        $model = $this->previewThreeFactory->create();
        $model->setData($dataSave);
        try {
            $this->resPreviewThreeFactory->create()->save($model);
            return true;
        }
        catch (\Exception $exception) {

        }
        return  true;
    }
}
