<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
namespace EasyWeChat\BasicService\Jssdk;

use EasyWeChat\Kernel\BaseClient;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use EasyWeChat\Kernel\Support;
use EasyWeChat\Kernel\Traits\InteractsWithCache;
/**
 * Class Client.
 *
 * @author overtrue <i@overtrue.me>
 */
class Client extends BaseClient
{
    use InteractsWithCache;
    /**
     * @var string
     */
    protected $ticketEndpoint = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket';
    /**
     * Current URI.
     *
     * @var string
     */
    protected $url;
    /**
     * Get config json for jsapi.
     *
     * @param array       $jsApiList
     * @param        $debug
     * @param        $beta
     * @param        $json
     * @param array       $openTagList
     * @param string|null $url
     *
     * @return array|string
     *
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function buildConfig(array $jsApiList, $debug = false, $beta = false, $json = true, array $openTagList = [], $url = null)
    {
        $config = array_merge(compact('debug', 'beta', 'jsApiList', 'openTagList'), $this->configSignature($url));
        return $json ? json_encode($config) : $config;
    }
    /**
     * Return jsapi config as a PHP array.
     *
     * @param array       $apis
     * @param        $debug
     * @param        $beta
     * @param array       $openTagList
     * @param string|null $url
     *
     * @return array|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getConfigArray(array $apis, $debug = false, $beta = false, array $openTagList = [], $url = null)
    {
        return $this->buildConfig($apis, $debug, $beta, false, $openTagList, $url);
    }
    /**
     * Get js ticket.
     *
     * @param   $refresh
     * @param $type
     *
     * @return array
     *
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getTicket($refresh = false, $type = 'jsapi')
    {
        $cacheKey = sprintf('easywechat.basic_service.jssdk.ticket.%s.%s', $type, $this->getAppId());
        if (!$refresh && $this->getCache()->has($cacheKey)) {
            return $this->getCache()->get($cacheKey);
        }
        /** @var array<string, mixed> $result */
        $result = $this->castResponseToType($this->requestRaw($this->ticketEndpoint, 'GET', ['query' => ['type' => $type]]), 'array');
        $this->getCache()->set($cacheKey, $result, $result['expires_in'] - 500);
        if (!$this->getCache()->has($cacheKey)) {
            throw new RuntimeException('Failed to cache jssdk ticket.');
        }
        return $result;
    }
    /**
     * Build signature.
     *
     * @param string|null $url
     * @param string|null $nonce
     * @param null        $timestamp
     *
     * @return array
     *
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function configSignature($url = null, $nonce = null, $timestamp = null)
    {
        $url = $url ?: $this->getUrl();
        $nonce = $nonce ?: Support\Str::quickRandom(10);
        $timestamp = $timestamp ?: time();
        return ['appId' => $this->getAppId(), 'nonceStr' => $nonce, 'timestamp' => $timestamp, 'url' => $url, 'signature' => $this->getTicketSignature($this->getTicket()['ticket'], $nonce, $timestamp, $url)];
    }
    /**
     * Sign the params.
     *
     * @param $ticket
     * @param $nonce
     * @param int    $timestamp
     * @param $url
     *
     * @return string
     */
    public function getTicketSignature($ticket, $nonce, $timestamp, $url)
    {
        return sha1(sprintf('jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s', $ticket, $nonce, $timestamp, $url));
    }
    /**
     * @return string
     */
    public function dictionaryOrderSignature()
    {
        $params = func_get_args();
        sort($params, SORT_STRING);
        return sha1(implode('', $params));
    }
    /**
     * Set current url.
     *
     * @param $url
     *
     * @return $this
     */
    public function setUrl($url)
    {
        $this->url = $url;
        return $this;
    }
    /**
     * Get current url.
     *
     * @return string
     */
    public function getUrl()
    {
        if ($this->url) {
            return $this->url;
        }
        return Support\current_url();
    }
    /**
     * @return string
     */
    protected function getAppId()
    {
        return $this->app['config']->get('app_id');
    }
    /**
     * @return string
     */
    protected function getAgentId()
    {
        return $this->app['config']->get('agent_id');
    }
}