package com.sinewang.statemate.core.spi;

import one.kii.statemate.core.spi.CreateExtensionSpi;
import one.kii.summer.io.exception.*;
import one.kii.summer.io.sender.ErestPost;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by WangYanJiong on 4/7/17.
 */
@ConfigurationProperties(prefix = "metamate")
@Component
public class DefaultCreateExtensionSpi implements CreateExtensionSpi {

    private static Logger logger = LoggerFactory.getLogger(DefaultCreateExtensionSpi.class);

    private static String URI = "/{ownerId}/extension";
    private static String TREE = "master";
    private static String VISIBILITY_PUBLIC = "public";
    private String baseUrl;

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    @Override
    public Receipt createMasterPublicExtension(Form form) throws Panic {
        String url = baseUrl + URI;

        ErestPost erest = new ErestPost(form.getOwnerId());
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.put("group", toList(form.getGroup()));
        map.put("name", toList(form.getName()));
        map.put("tree", toList(TREE));
        map.put("visibility", toList(VISIBILITY_PUBLIC));
        try {
            return erest.execute(url, map, Receipt.class, form.getOwnerId());
        } catch (Conflict conflict) {
            Receipt receipt = new Receipt();
            receipt.setId(conflict.getKeys()[0]);
            return receipt;
        } catch (NotFound notFound) {
            logger.error("not-found:{}", notFound.getKey());
            throw new Panic();
        } catch (BadRequest | Forbidden | Panic panic) {
            logger.error("", panic);
            throw new Panic();
        }
    }

    private List<String> toList(String string) {
        List<String> list = new ArrayList<>();
        list.add(string);
        return list;
    }

}

@@ -1312,18 +1312,18 @@
     map.
-pu
+se
 t(%22group
@@ -1325,23 +1325,16 @@
 group%22, 
-toList(
 form.get
@@ -1341,17 +1341,16 @@
 Group())
-)
 ;%0A      
@@ -1355,18 +1355,18 @@
     map.
-pu
+se
 t(%22name%22
@@ -1367,23 +1367,16 @@
 %22name%22, 
-toList(
 form.get
@@ -1382,17 +1382,16 @@
 tName())
-)
 ;%0A      
@@ -1396,18 +1396,18 @@
     map.
-pu
+se
 t(%22tree%22
@@ -1412,21 +1412,13 @@
 e%22, 
-toList(
 TREE)
-)
 ;%0A  
@@ -1427,18 +1427,18 @@
     map.
-pu
+se
 t(%22visib
@@ -1445,23 +1445,16 @@
 ility%22, 
-toList(
 VISIBILI
@@ -1463,17 +1463,16 @@
 _PUBLIC)
-)
 ;%0A      

update multvaluemap, using set instead of put