<?php
/**
 * TNT OFFICIAL MODULE FOR PRESTASHOP
 *
 * @author    GFI Informatique <www.gfi.fr>
 * @copyright 2016-2017 GFI Informatique, 2016-2017 TNT
 * @license   https://opensource.org/licenses/MIT MIT License
 */

require_once _PS_MODULE_DIR_.'tntofficiel/tntofficiel.php';

class TNTOfficiel_Logger extends AbstractLogger
{
    /**
     * @param $request
     * @param null $message
     * @param string $format
     * @param bool|false $isRequest
     * @param null $status
     * @param null $data
     * @return bool
     */
    public function logMessageTnt($request, $message = null, $format = 'JSON', $isRequest = false, $status = null, $data = null)
    {
        try {
            $this->_createLogFolder();
            if ($isRequest) {
                $formattedMessage = $this->_formatMessageRequest($status, $format, $request);
            } else {
                $formattedMessage = $this->_formatErrorMessage($message, $format, $request, $data);
            }
        } catch (Exception $objException) {
            $objFileLogger = new FileLogger();
            $objFileLogger->setFilename(_PS_ROOT_DIR_.'/log/'.date('Ymd').'_tnt_exception.log');
            $objFileLogger->logError($objException->getMessage());
        }

        $strLogPath = _PS_MODULE_DIR_.TNTOfficiel::MODULE_NAME.'/'.TNTOfficiel::LOG_DIR;
        return (bool)file_put_contents($strLogPath.$this->_getFileName($isRequest), $formattedMessage, FILE_APPEND);
    }

    public function logMessage($message, $level)
    {

    }

    /**
     * Creates the log folder if not exist
     */
    private function _createLogFolder()
    {
        $strLogPath = _PS_MODULE_DIR_.TNTOfficiel::MODULE_NAME.'/'.TNTOfficiel::LOG_DIR;
        if (!is_dir($strLogPath)) {
            mkdir($strLogPath, 0777, true);
        }
    }

    /**
     * Return the log file name
     * @param $isRequest
     * @return string
     */
    private function _getFileName($isRequest)
    {
        $dateTime = new DateTime();
        $date = $dateTime->format('Ymd');
        if ($isRequest) {
            $fileName = sprintf('TNT-request-%s', $date);
        } else {
            $fileName = sprintf('TNT-errors-%s', $date);
        }

        return $fileName.'.log';
    }

    /**
     * Format the message for a request log
     * @param $status
     * @param $format
     * @param $request
     * @return string
     */
    private function _formatMessageRequest($status, $format, $request)
    {
        $dateTime = new DateTime();
        $date = $dateTime->format('Ymd H:i:s');
        $account = Configuration::get('TNT_CARRIER_ACCOUNT');
        $formattedMessage = sprintf('%s - %s %s %s:%s %s', $date, $account, $status, $format, $request, chr(10));

        return $formattedMessage;
    }

    /**
     * Format the message for an error log
     * @param $message
     * @param $format
     * @param $request
     * @param $data
     * @return string
     */
    private function _formatErrorMessage($message, $format, $request, $data)
    {
        $dateTime = new DateTime();
        $date = $dateTime->format('Ymd H:i:s');
        $account = Configuration::get('TNT_CARRIER_ACCOUNT');
        $formattedMessage = sprintf('%s - %s %s:%s Error %s || %s %s', $date, $account, $format, $request, $message, $data, chr(10));

        return $formattedMessage;
    }

    /**
     * Log install and uninstall steps
     * @param $message
     * @return bool
     */
    public function logInstall($message)
    {
        $dateTime = new DateTime();
        $date = $dateTime->format('Ymd H:i:s');
        $logMessage = sprintf('%s %s %s', $date, $message, chr(10));
        $filename = 'install.log';
        try {
            $this->_createLogFolder();
        } catch (Exception $objException) {
            $objFileLogger = new FileLogger();
            $objFileLogger->setFilename(_PS_ROOT_DIR_.'/log/'.date('Ymd').'_tnt_exception.log');
            $objFileLogger->logError($objException->getMessage());
        }

        $strLogPath = _PS_MODULE_DIR_.TNTOfficiel::MODULE_NAME.'/'.TNTOfficiel::LOG_DIR;
        return (bool)file_put_contents($strLogPath.$filename, $logMessage, FILE_APPEND);
    }

    /**
     * Log install and uninstall steps
     * @param $message
     * @return bool
     */
    public function logUninstall($message)
    {
        $dateTime = new DateTime();
        $date = $dateTime->format('Ymd H:i:s');
        $logMessage = sprintf('%s %s %s', $date, $message, chr(10));
        $filename = 'uninstall.log';
        try {
            $this->_createLogFolder();
        } catch (Exception $objException) {
            $objFileLogger = new FileLogger();
            $objFileLogger->setFilename(_PS_ROOT_DIR_.'/log/'.date('Ymd').'_tnt_exception.log');
            $objFileLogger->logError($objException->getMessage());
        }

        $strLogPath = _PS_MODULE_DIR_.TNTOfficiel::MODULE_NAME.'/'.TNTOfficiel::LOG_DIR;
        return (bool)file_put_contents($strLogPath.$filename, $logMessage, FILE_APPEND);
    }

    /**
     * Generate an archive containing all the logs files
     *
     * @param $zipName
     * @return ZipArchive
     */
    public static function getZip($zipName)
    {
        $strLogPath = _PS_MODULE_DIR_.TNTOfficiel::MODULE_NAME.'/'.TNTOfficiel::LOG_DIR;
        $files = scandir($strLogPath);

        $zip = new ZipArchive();
        $zip->open($zipName, ZipArchive::CREATE);
        foreach ($files as $file) {
            $filePath = $strLogPath.$file;
            $strExt = pathinfo($file, PATHINFO_EXTENSION);
            if (in_array($strExt, array('log', 'json'), true) && file_exists($filePath)) {
                $zip->addFromString(basename($filePath), Tools::file_get_contents($filePath));
            }
        }
        $zip->close();
        return $zip;
    }

}