package org.wso2.carbon.device.mgt.ios.api.utils.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.wso2.carbon.device.mgt.ios.api.utils.beans.Application;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class ApplicationUtils {

    private static final String SHORT_VERSION = "ShortVersion";
    private static final String BUNDLE_SIZE = "BundleSize";
    private static final String DYNAMIC_SIZE = "DynamicSize";

    public List<org.wso2.carbon.device.mgt.common.app.mgt.Application> parseApplicationList(String applicationList) {

        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<Application>>() {}.getType();
        List<Application> applications = gson.fromJson(applicationList, listType);

        List<org.wso2.carbon.device.mgt.common.app.mgt.Application> commonAppList =
                new ArrayList<org.wso2.carbon.device.mgt.common.app.mgt.Application>();
        for (Application application : applications) {

            org.wso2.carbon.device.mgt.common.app.mgt.Application commonApp =
                    new org.wso2.carbon.device.mgt.common.app.mgt.Application();
            commonApp.setApplicationIdentifier(application.getIdentifier());
            commonApp.setName(application.getName());
            commonApp.setVersion(application.getVersion());

            Properties applicationProperties = new Properties();

            if(application.getShortVersion() != null) {
                applicationProperties.put(SHORT_VERSION, application.getShortVersion());
            }

            if(application.getBundleSize() != null) {
                applicationProperties.put(BUNDLE_SIZE, application.getBundleSize());
            }

            if(application.getDynamicSize() != null) {
                applicationProperties.put(DYNAMIC_SIZE, application.getDynamicSize());
            }

            commonApp.setAppProperties(applicationProperties);

            commonAppList.add(commonApp);
        }

        return commonAppList;
    }
}