<?php

namespace Api\PhpServices\ChameleonPackage;


use Api\PhpUtils\Redis\Codis;

class Package
{
    /**
     * 将包信息存储到 redis，若 package_version 已存在，则更新
     * @param $appid
     * @param $package_version
     * @param $data
     */
    public static function save( string $appid, $package_version, array $data ){
        $redis  = (new Codis())->getInstance();
        $key    =  config("redis","key.prefix.ChameleonPackage").$appid."_".$package_version;
        $old    = $redis->get($key);

        $json   = self::getJson($data);
        if($json){
            $data["json"] = $json;
        }

        if($old){
            $old    = json_decode($old, true);
            $data   = array_merge($old, $data);
        }

        $data   = json_encode($data);
        return $redis->set($key, $data);
    }


    /**
     * 获取指定版本的所有包信息
     * @param string $appid
     * @param $package_version
     * @return bool|mixed|string
     */
    public static function getAll(string $appid, $package_version){
        $key    =  config("redis","key.prefix.ChameleonPackage").$appid."_".$package_version;
        $redis  = (new Codis())->getInstance();
        $res = $redis->get($key);
        return json_decode($res, true);
    }

    
    /**
     * 仅获取json 信息
     * @param string $appid
     * @param $package_version
     * @return mixed
     */
    public static function getInfo(string $appid, $package_version){
        $key    =  config("redis","key.prefix.ChameleonPackage").$appid."_".$package_version;
        $redis  = (new Codis())->getInstance();
        $res = $redis->get($key);
        if(!$res){
            return [];
        }
        $res = json_decode($res, true);
        return $res["json"] ?? [];
    }


    /**
     * 目前约定把包中的 json 文件单独用extra字段传入，不需解压包提取
     * 若后期修改字段或需要解压，在此方法中操作提取json返回即可
     * @param $data
     * @return mixed|string
     */
    private static function getJson($data){
        return $data["extra"]??"";
    }
}