package peergos.shared.storage;

import jsinterop.annotations.*;
import peergos.shared.cbor.*;

import java.util.*;

public final class PaymentProperties  implements Cborable {

    public final Optional<String> paymentServerUrl;
    public final String clientSecret;
    public final long desiredQuota;

    public PaymentProperties() {
        this.paymentServerUrl = Optional.empty();
        this.clientSecret = "";
        this.desiredQuota = 0;
    }

    public PaymentProperties(String paymentServerUrl, String clientSecret, long desiredQuota) {
        this.paymentServerUrl = Optional.of(paymentServerUrl);
        this.clientSecret = clientSecret;
        this.desiredQuota = desiredQuota;
    }

    @JsMethod
    public boolean isPaid() {
        return paymentServerUrl.isPresent();
    }

    @JsMethod
    public String getUrl() {
        return paymentServerUrl.get();
    }

    @JsMethod
    public String getClientSecret() {
        return clientSecret;
    }

    @Override
    public CborObject toCbor() {
        SortedMap<String, Cborable> state = new TreeMap<>();
        state.put("desiredQuota", new CborObject.CborLong(desiredQuota));
        paymentServerUrl.ifPresent(url -> state.put("url", new CborObject.CborString(url)));
        if (clientSecret.length() > 0)
            state.put("client_secret", new CborObject.CborString(clientSecret));
        return CborObject.CborMap.build(state);
    }

    public static PaymentProperties fromCbor(Cborable cbor) {
        if (! (cbor instanceof CborObject.CborMap))
            throw new IllegalStateException("Invalid cbor for FileProperties! " + cbor);
        CborObject.CborMap m = (CborObject.CborMap) cbor;
        Optional<String> url = m.getOptional("url", c -> ((CborObject.CborString)c).value);
        Optional<String> client_secret = m.getOptional("client_secret", c -> ((CborObject.CborString) c).value);
        long desiredQuota = m.getLong("desiredQuota");
        if (url.isPresent())
            return new PaymentProperties(url.get(), client_secret.orElse(""), desiredQuota);
        return new PaymentProperties();
    }
}

@@ -240,22 +240,32 @@
 c final 
+Optional%3C
 String
+%3E
  clientS
@@ -419,18 +419,32 @@
 ecret = 
-%22%22
+Optional.empty()
 ;%0A      
@@ -529,22 +529,32 @@
 verUrl, 
+Optional%3C
 String
+%3E
  clientS
@@ -995,24 +995,35 @@
 clientSecret
+.orElse(%22%22)
 ;%0A    %7D%0A%0A   
@@ -1323,20 +1323,19 @@
 ret.
-length() %3E 0
+isPresent()
 )%0A  
@@ -1409,16 +1409,22 @@
 ntSecret
+.get()
 ));%0A    
@@ -2089,27 +2089,16 @@
 t_secret
-.orElse(%22%22)
 , desire

clean up PaymentProperties