package com.apobates.forum.member.storage.cookie;

import java.io.Serializable;
import java.util.Objects;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.CookieUtils;
/**
 * 客户端每次请求需要携带的载荷
 * 
 * @author xiaofanku
 * @since 20200120
 */
public final class StorageSerialize implements Serializable{
    private static final long serialVersionUID = 6413667918010225786L;
    private final String factor;
    private final String hash;
    
    public StorageSerialize(String factor, String hash) {
        super();
        this.factor = factor;
        this.hash = hash;
    }
    
    public String getFactor() {
        return factor;
    }
    
    public String getHash() {
        return hash;
    }
    
    @Override
    public String toString() {
        if (Commons.isNotBlank(getHash()) && Commons.isNotBlank(getFactor())) {
            String data = String.format("hash:%s,factor:%s", getHash(), getFactor());
            return CookieUtils.encodeCookieValue(data, "");
        }
        throw new IllegalArgumentException("[OM][SS]serialize field is Illegal");
    }
    
    public static StorageSerialize getInstance(String cookieValue) {
        Objects.requireNonNull(cookieValue);
        //
        if (!Commons.isNotBlank(cookieValue)) {
            throw new IllegalArgumentException("[OM][SS]serialize from argument is Illegal");
        }
        //
        String decodeCV = CookieUtils.decodeCookieValue(cookieValue, null);
        if (null == decodeCV) {
            throw new IllegalArgumentException("[OM][SS]serialize decode fail");
        }
        //hash:%s,factor:%s
        String[] data = decodeCV.split(",");
        if (data.length != 2) {
            throw new IllegalStateException("[OM][SS]serialize from argument is lost part");
        }
        return new StorageSerialize(data[1].replace("factor:", ""), data[0].replace("hash:", ""));
    }
}
