<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 4/30/17
 * Time: 1:45 PM
 */

namespace IMATHUZH\Qfq\Core\Helper;


/**
 * Class SessionCookie
 * @package qfq
 */
class SessionCookie {

    /**
     * @var string
     */
    private $pathFileNameCookie = '';

    /**
     * @var array
     */
    private $arrQfqPdfCookie = array();

    /**
     * @var bool
     */
    private $cleanTempFiles = true;

    /**
     * Copy all current cookies to a temporary file.
     *
     * @param array $config
     *
     * @throws \CodeException
     */
    public function __construct(array $config) {
        $wkhtml = array();

        // In debug mode, keep temporary files
        $this->cleanTempFiles = !Support::findInSet(SYSTEM_SHOW_DEBUG_INFO_DOWNLOAD, $config[SYSTEM_SHOW_DEBUG_INFO]);

        $urlParts = parse_url($config[SYSTEM_BASE_URL]);
        $domain = $urlParts['host'] ?? 'missing';
        $path = $urlParts['path'] ?? 'missing';

        // $_COOKIES[]
        if (false === ($this->pathFileNameCookie = tempnam(sys_get_temp_dir(), SESSION_COOKIE_PREFIX))) {
            throw new \CodeException('Error creating output file.', ERROR_IO_CREATE_FILE);
        }

        // wkhtml
//        foreach ($_COOKIE as $name => $value) {
//            // e.g.: SANDBOXSESSION=a83f1o69jbv12932q54hmgphk6; domain=qfq.math.uzh.ch; path=/;
//            $data .= $name . "=" . $value . "; domain=$domain; path=$path;\n";
//        }

//        "expires": 1633622615.629729,
//        "size": 16,
//        "httpOnly": true,
//        "secure": true,
//        "session": false,
//        "sameSite": "Lax"

        // Prepare cookie for wkhtml & qfqpdf
        foreach ($_COOKIE as $key => $value) {
            $wkhtml[] = ['name' => $key, 'value' => $value, 'url' => $domain, 'path' => $path];

//            $this->arrCookieString[] = "name:$key,value:$value,url:$domain,path:$path";
            // qfqpdf seems to have problems if 'domain' is specified: it hangs by fetching the website. Skip domain.
            // qfqpdf generates another cookie for pdf (SIPs then not reachable) if the given domain doesnt equal what is set in cookie params. Domain default from qfqpdf is without dot. We need to give the domain with previous dot.
            $this->arrQfqPdfCookie[] = "name:$key,value:$value";
        }
        $linesForWkhtml = '';
        for ($i = 0; $i < count($wkhtml); $i++) {
            $linesForWkhtml .= $wkhtml[$i]['name'] . "=" . $wkhtml[$i]['value'] . "; domain=" . $wkhtml[$i]['url'] . "; " . "path=" . $wkhtml[$i]['path'] . ";";
            if ($i + 1 < count($wkhtml)) {
                $linesForWkhtml .= "\n";
            }
        }

        file_put_contents($this->pathFileNameCookie, $linesForWkhtml, FILE_APPEND);
    }

    /**
     * Unlink current cookie file
     * @throws \UserFormException
     * @throws \CodeException
     */
    public function __destruct() {

        if ($this->cleanTempFiles) {
            if (file_exists($this->pathFileNameCookie)) {
                HelperFile::unlink($this->pathFileNameCookie);
                $this->pathFileNameCookie = '';
            }
        }
    }

    /**
     * @return string PathFilename of cookie file
     */
    public function getFile() {

        return $this->pathFileNameCookie;
    }

    /**
     * Returns a string, with optional several cookies, separeted by space
     * Example: '"name:firstCookie,value:tunjngvnjfr23r" "name:secondCookie,value:249ur4jn233d"'
     * @return string
     */
    public function getCookieQfqPdf() {
        return '"' . implode('" "', $this->arrQfqPdfCookie) . '"';
    }
}