package org.gcube.application.geoportal.service.ws;

import org.gcube.application.cms.tests.TokenSetter;
import org.gcube.common.storagehub.client.dsl.FolderContainer;
import org.gcube.common.storagehub.client.dsl.StorageHubClient;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.items.AbstractFileItem;
import org.gcube.common.storagehub.model.items.FolderItem;
import org.gcube.common.storagehub.model.items.Item;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.List;

public class DescribeWSFolder {


    static StorageHubClient shc =null;

    public static void main(String[] args) throws StorageHubException {
        String context="/gcube/devsec/devVRE";
        String folderID="...";
        Boolean recursive = false;

        TokenSetter.set(context);
        shc= new StorageHubClient();
        shc.openVREFolder().get().getDescription();

        FolderContainer folder=shc.open(folderID).asFolder();
      //  FolderContainer folder = WorkspaceManager.getApplicationBaseFolder(shc);

        FolderItem item=folder.get();
            System.out.print("PATH : "+item.getPath()+"\tHIDDEN : "+item.isHidden()+"\tDescription : "+item.getDescription());

        System.out.println("Listing... ");
        Long size=print(folder,"",recursive);
        System.out.println("Size : "+humanReadableByteCountBin(size));
    }

    private static final Long print(FolderContainer folder,String pad,Boolean recursive) throws StorageHubException {
        Long toReturn=new Long(0);
        List<? extends Item> items =folder.list().includeHidden().withContent().getItems();
        System.out.println(pad+"Elements : "+items.size());
        for (Item i :  items) {
            System.out.println(pad+ i.getName() + " [" + i.getPrimaryType()+"]");
            if(i instanceof FolderItem){
                if(recursive)
                    toReturn+= print(shc.open(i.getId()).asFolder(),pad+"\t",recursive);
            }else if (i instanceof AbstractFileItem){
//                toReturn+=shc.open(i.getId()).asFile().get().getContent().getSize();
                toReturn+=((AbstractFileItem) i).getContent().getSize();
            }
        }
        return toReturn;
    }

    public static String humanReadableByteCountBin(long bytes) {
        long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
        if (absB < 1024) {
            return bytes + " B";
        }
        long value = absB;
        CharacterIterator ci = new StringCharacterIterator("KMGTPE");
        for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) {
            value >>= 10;
            ci.next();
        }
        value *= Long.signum(bytes);
        return String.format("%.1f %ciB", value / 1024.0, ci.current());
    }
}
