<?php


namespace App\Controllers;

use App\DAO\Filter\QueryFilter;
use App\DAO\Filter\QueryFilterTranslator;
use App\DAO\Order\QueryOrderTranslator;
use App\Services\GaleriaService;
use App\Services\ServiceResponse\ServiceResponseInterface;
use App\Utils\Collections\QueryFilterCollection;
use App\Utils\Collections\QueryOrderCollection;
use App\Validations\GaleriaValidation;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Paths;
use Exception;

class GaleriaController extends BaseController
{

    function registerGaleria()
    {
        $data_post = $this->getDataPost();

        if (!$this->validate(GaleriaValidation::register())) {
            return $this->response->setJSON([
                'message' => 'Informe os dados corretamente.',
                'errors' => $this->validation->getErrors()
            ]);
        }

        $encoded_string = $data_post['image'];
        $paths = new Paths();
        //$target_dir = $paths->writableDirectory . '/images/'. $data_post['id_paciente'] . '/'; // add the specific path to save the file

        $target_dir = '../writable/images/'.$data_post['id_clinica'] .'/';
        if(!is_dir($target_dir)) {mkdir($target_dir);}
        $target_dir = $target_dir.$data_post['id_medico'].'/';
        if(!is_dir($target_dir)) {mkdir($target_dir);}
        $target_dir = $target_dir.$data_post['id_paciente'] .'/';
        if(!is_dir($target_dir)) {mkdir($target_dir);}

        $mime_type = finfo_buffer(finfo_open(), $encoded_string, FILEINFO_MIME_TYPE); // extract mime type
        $extension = $this->mime2ext($mime_type); // extract extension from mime type
        $file = uniqid() . '.' . $extension; // rename file as a unique name
        $file_dir = $target_dir . uniqid() . '.' . $extension;
        try {
            file_put_contents($file_dir, $encoded_string);
            header('Content-Type: application/json');
            $assistente_service_response = (new GaleriaService())->registerGaleria($data_post, $file_dir);
            $response_messages = [
                ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [
                    'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                    'message' => 'Erro de conexão com o banco de dados.'
                ],
                ServiceResponseInterface::SUCESS => [
                    'code' => ResponseInterface::HTTP_OK,
                    'message' => 'A foto foi cadastrada com sucesso.'
                ],
                ServiceResponseInterface::VALIDATION_PARAMS_ERROR => [
                    'code' => ResponseInterface::HTTP_BAD_REQUEST,
                    'message' => 'Informe os dados corretamente.'
                ],
                ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [
                    'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                    'message' => 'Erro interno do servidor.'
                ],
            ];
            $status = $assistente_service_response->toArray();
            if($status["status"] == 6){
                unlink($file_dir);
            }

            return $this->getResponse($assistente_service_response, $response_messages);
        } catch (Exception $e) {
            return(json_encode($e->getMessage()));
        }
    }

    function getGaleriaList(){
        $pagination = $this->getPaginationFromRequest();
        $query_filter_collection = new QueryFilterCollection($_GET, QueryFilterTranslator::galeria());
        //var_dump(count($query_filter_collection->toArray()));
        if (count($query_filter_collection->toArray()) === 0){
            return $this->response->setJSON([
                'data' => '{}',
                'message' => 'É necessário especificar o paciente.',
                'errors' => $this->validation->getErrors()
            ]);
        }

        $query_order_collection = new QueryOrderCollection($_GET, QueryOrderTranslator::galeria());

        $procedimento_service_response = (new GaleriaService())->getGaleriaList($pagination, $query_filter_collection, $query_order_collection);
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'Os dados da galeria foram encontrados com sucesso.'
            ],
            ServiceResponseInterface::RECORD_NOT_FOUND => [
                'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
                'message' => 'Nenhum registro foi encontrado.'
            ],
            ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ],
            ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ],
        ];
        return $this->getResponse($procedimento_service_response, $response_messages);
    }

    public function searchGaleriaByID (int $id_galeria) : Response {
        $query_filter = QueryFilter::builder()
            ->setTable('galeria')
            ->setNameParam('id')
            ->setValue($id_galeria)
            ->setIsExact(true)
            ->build();
        $erro_service_response = (new GaleriaService())->getGaleria($query_filter);
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'Os dados do exame foram encontrados com sucesso.'
            ],
            ServiceResponseInterface::RECORD_NOT_FOUND => [
                'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
                'message' => 'Nenhum registro foi encontrado.'
            ],
            ServiceResponseInterface::SERVICE_INTERNAL_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ],
            ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ],
        ];
        return $this->getResponse($erro_service_response, $response_messages);
    }

    function mime2ext($mime){
        $all_mimes = '{"png":["image\/png","image\/x-png"],"bmp":["image\/bmp","image\/x-bmp",
    "image\/x-bitmap","image\/x-xbitmap","image\/x-win-bitmap","image\/x-windows-bmp",
    "image\/ms-bmp","image\/x-ms-bmp","application\/bmp","application\/x-bmp",
    "application\/x-win-bitmap"],"gif":["image\/gif"],"jpeg":["image\/jpeg",
    "image\/pjpeg"],"xspf":["application\/xspf+xml"],"vlc":["application\/videolan"],
    "wmv":["video\/x-ms-wmv","video\/x-ms-asf"],"au":["audio\/x-au"],
    "ac3":["audio\/ac3"],"flac":["audio\/x-flac"],"ogg":["audio\/ogg",
    "video\/ogg","application\/ogg"],"kmz":["application\/vnd.google-earth.kmz"],
    "kml":["application\/vnd.google-earth.kml+xml"],"rtx":["text\/richtext"],
    "rtf":["text\/rtf"],"jar":["application\/java-archive","application\/x-java-application",
    "application\/x-jar"],"zip":["application\/x-zip","application\/zip",
    "application\/x-zip-compressed","application\/s-compressed","multipart\/x-zip"],
    "7zip":["application\/x-compressed"],"xml":["application\/xml","text\/xml"],
    "svg":["image\/svg+xml"],"3g2":["video\/3gpp2"],"3gp":["video\/3gp","video\/3gpp"],
    "mp4":["video\/mp4"],"m4a":["audio\/x-m4a"],"f4v":["video\/x-f4v"],"flv":["video\/x-flv"],
    "webm":["video\/webm"],"aac":["audio\/x-acc"],"m4u":["application\/vnd.mpegurl"],
    "pdf":["application\/pdf","application\/octet-stream"],
    "pptx":["application\/vnd.openxmlformats-officedocument.presentationml.presentation"],
    "ppt":["application\/powerpoint","application\/vnd.ms-powerpoint","application\/vnd.ms-office",
    "application\/msword"],"docx":["application\/vnd.openxmlformats-officedocument.wordprocessingml.document"],
    "xlsx":["application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application\/vnd.ms-excel"],
    "xl":["application\/excel"],"xls":["application\/msexcel","application\/x-msexcel","application\/x-ms-excel",
    "application\/x-excel","application\/x-dos_ms_excel","application\/xls","application\/x-xls"],
    "xsl":["text\/xsl"],"mpeg":["video\/mpeg"],"mov":["video\/quicktime"],"avi":["video\/x-msvideo",
    "video\/msvideo","video\/avi","application\/x-troff-msvideo"],"movie":["video\/x-sgi-movie"],
    "log":["text\/x-log"],"txt":["text\/plain"],"css":["text\/css"],"html":["text\/html"],
    "wav":["audio\/x-wav","audio\/wave","audio\/wav"],"xhtml":["application\/xhtml+xml"],
    "tar":["application\/x-tar"],"tgz":["application\/x-gzip-compressed"],"psd":["application\/x-photoshop",
    "image\/vnd.adobe.photoshop"],"exe":["application\/x-msdownload"],"js":["application\/x-javascript"],
    "mp3":["audio\/mpeg","audio\/mpg","audio\/mpeg3","audio\/mp3"],"rar":["application\/x-rar","application\/rar",
    "application\/x-rar-compressed"],"gzip":["application\/x-gzip"],"hqx":["application\/mac-binhex40",
    "application\/mac-binhex","application\/x-binhex40","application\/x-mac-binhex40"],
    "cpt":["application\/mac-compactpro"],"bin":["application\/macbinary","application\/mac-binary",
    "application\/x-binary","application\/x-macbinary"],"oda":["application\/oda"],
    "ai":["application\/postscript"],"smil":["application\/smil"],"mif":["application\/vnd.mif"],
    "wbxml":["application\/wbxml"],"wmlc":["application\/wmlc"],"dcr":["application\/x-director"],
    "dvi":["application\/x-dvi"],"gtar":["application\/x-gtar"],"php":["application\/x-httpd-php",
    "application\/php","application\/x-php","text\/php","text\/x-php","application\/x-httpd-php-source"],
    "swf":["application\/x-shockwave-flash"],"sit":["application\/x-stuffit"],"z":["application\/x-compress"],
    "mid":["audio\/midi"],"aif":["audio\/x-aiff","audio\/aiff"],"ram":["audio\/x-pn-realaudio"],
    "rpm":["audio\/x-pn-realaudio-plugin"],"ra":["audio\/x-realaudio"],"rv":["video\/vnd.rn-realvideo"],
    "jp2":["image\/jp2","video\/mj2","image\/jpx","image\/jpm"],"tiff":["image\/tiff"],
    "eml":["message\/rfc822"],"pem":["application\/x-x509-user-cert","application\/x-pem-file"],
    "p10":["application\/x-pkcs10","application\/pkcs10"],"p12":["application\/x-pkcs12"],
    "p7a":["application\/x-pkcs7-signature"],"p7c":["application\/pkcs7-mime","application\/x-pkcs7-mime"],"p7r":["application\/x-pkcs7-certreqresp"],"p7s":["application\/pkcs7-signature"],"crt":["application\/x-x509-ca-cert","application\/pkix-cert"],"crl":["application\/pkix-crl","application\/pkcs-crl"],"pgp":["application\/pgp"],"gpg":["application\/gpg-keys"],"rsa":["application\/x-pkcs7"],"ics":["text\/calendar"],"zsh":["text\/x-scriptzsh"],"cdr":["application\/cdr","application\/coreldraw","application\/x-cdr","application\/x-coreldraw","image\/cdr","image\/x-cdr","zz-application\/zz-winassoc-cdr"],"wma":["audio\/x-ms-wma"],"vcf":["text\/x-vcard"],"srt":["text\/srt"],"vtt":["text\/vtt"],"ico":["image\/x-icon","image\/x-ico","image\/vnd.microsoft.icon"],"csv":["text\/x-comma-separated-values","text\/comma-separated-values","application\/vnd.msexcel"],"json":["application\/json","text\/json"]}';
        $all_mimes = json_decode($all_mimes,true);
        foreach ($all_mimes as $key => $value) {
            if(array_search($mime,$value) !== false) return $key;
        }
        return false;
    }

    public function deleteGaleria (int $id_galeria) {
        $erro_service_response = (new GaleriaService())->deleteGaleria($id_galeria);
        $response_messages = [
            ServiceResponseInterface::SUCESS => [
                'code' => ResponseInterface::HTTP_OK,
                'message' => 'A exclusão foi efetuda com sucesso.'
            ],
            ServiceResponseInterface::RECORD_NOT_FOUND => [
                'code' => ResponseInterface::HTTP_PARTIAL_CONTENT,
                'message' => 'Nenhum registro foi encontrado.'
            ],
            ServiceResponseInterface::RECORD_IS_LINKED => [
                'code' => ResponseInterface::HTTP_BAD_REQUEST,
                'message' => 'Essa foto está vinculada a outros cadastros do sistema. Portanto, não pode ser excluído.'
            ],
            ServiceResponseInterface::DATABASE_CONNECTION_ERROR => [
                'code' => ResponseInterface::HTTP_INTERNAL_SERVER_ERROR,
                'message' => 'Erro interno do servidor.'
            ],
        ];
        return $this->getResponse($erro_service_response, $response_messages);
    }

}
