package org.zstack.test.applianceVm;

import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.SimpleQuery;
import org.zstack.header.configuration.DiskOfferingInventory;
import org.zstack.header.identity.AccountInventory;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmNicVO;
import org.zstack.header.vm.VmNicVO_;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.test.identity.IdentityCreator;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

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

/**
 * Created by miao on 16-9-2.
 */
public class TestChangeOwnerOfVm {
    CLogger logger = Utils.getLogger(TestChangeOwnerOfVm.class);
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;
    SessionInventory session;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/vm/TestChangeOwnerOfVm.xml", con);
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
        session = api.loginAsAdmin();
    }

    @Test
    public void test() throws ApiSenderException {
        IdentityCreator identityCreator = new IdentityCreator(api);
        identityCreator.useAccount("test");
        VmInstanceInventory vm = deployer.vms.get("TestVm");
        DiskOfferingInventory dinv = deployer.diskOfferings.get("TestDataDiskOffering1");
        VolumeInventory vi = api.createDataVolume("data", dinv.getUuid());
        api.attachVolumeToVm(vm.getUuid(), vi.getUuid());
        // create volume snapshot
        String volUuid = vm.getRootVolumeUuid();
        VolumeSnapshotInventory inv = api.createSnapshot(volUuid);

        ArrayList<String> sharedResources = new ArrayList<>();
        ArrayList<String> accountList = new ArrayList<>();
        accountList.add(deployer.accounts.get("test2").getUuid());
        deployer.l3Networks.forEach(
                (s, l3NetworkInventory) -> sharedResources.add(l3NetworkInventory.getUuid()));
        api.shareResource(sharedResources, accountList, false);

        // change owner for the same account
        try {
            api.changeResourceOwner(vm.getUuid(), identityCreator.getAccountSession().getAccountUuid());
        } catch (Exception e) {

        }

        // change owner for the different account
        identityCreator.useAccount("test2");
        String targetAccountUuid = identityCreator.getAccountSession().getAccountUuid();
        api.changeResourceOwner(vm.getUuid(), targetAccountUuid);
        ArrayList<String> resUuids = new ArrayList<>();
        resUuids.add(vm.getRootVolumeUuid());
        resUuids.add(vi.getUuid());
        // add vmnics of vm
        SimpleQuery<VmNicVO> sq = dbf.createQuery(VmNicVO.class);
        sq.select(VmNicVO_.uuid);
        sq.add(VmNicVO_.vmInstanceUuid, SimpleQuery.Op.EQ, vm.getUuid());
        List<String> vmnics = sq.listValue();
        if (vmnics.isEmpty()) {
            return;
        }
        for (String vmnicUuid : vmnics) {
            logger.debug("VmNic:" + vmnicUuid);
            resUuids.add(vmnicUuid);
        }
        //
        Map<String, AccountInventory> resAccMap = api.getResourceAccount(resUuids);
        assert (resAccMap.size() == resUuids.size());

        for (AccountInventory ai : resAccMap.values()) {
            logger.debug("begin");
            logger.debug(ai.getUuid());
            logger.debug(ai.getType());
            logger.debug("targetAccountUuid:" + targetAccountUuid);
            logger.debug("end");
            assert (ai.getUuid().equals(targetAccountUuid));
        }
    }
}


@@ -31,16 +31,47 @@
 nceVm;%0A%0A
+import junit.framework.Assert;%0A
 import o
@@ -437,32 +437,189 @@
 dentity.
-SessionInventory
+Quota;%0Aimport org.zstack.header.identity.QuotaInventory;%0Aimport org.zstack.header.identity.SessionInventory;%0Aimport org.zstack.header.storage.snapshot.VolumeSnapshotConstant
 ;%0Aimport
@@ -1112,21 +1112,105 @@
 k.utils.
-Utils
+CollectionUtils;%0Aimport org.zstack.utils.Utils;%0Aimport org.zstack.utils.function.Function
 ;%0Aimport
@@ -2257,32 +2257,56 @@
 or(api);%0A       
+ AccountInventory test =
  identityCreator
@@ -2757,19 +2757,82 @@
 (volUuid
-);%0A
+, identityCreator.getAccountSession());%0A%0A        // share resource
 %0A       
@@ -3206,24 +3206,940 @@
 t, false);%0A%0A
+        //%0A        List%3CQuota.QuotaUsage%3E usages = api.getQuotaUsage(test.getUuid(), null);%0A        %7B%0A            Quota.QuotaUsage snapshotNum = CollectionUtils.find(usages, new Function%3CQuota.QuotaUsage, Quota.QuotaUsage%3E() %7B%0A                @Override%0A                public Quota.QuotaUsage call(Quota.QuotaUsage arg) %7B%0A                    return VolumeSnapshotConstant.QUOTA_VOLUME_SNAPSHOT_NUM.equals(arg.getName()) ? arg : null;%0A                %7D%0A            %7D);%0A            Assert.assertNotNull(snapshotNum);%0A%0A            QuotaInventory quotaInventory = api.getQuota(%0A                    VolumeSnapshotConstant.QUOTA_VOLUME_SNAPSHOT_NUM,%0A                    test.getUuid(),%0A                    identityCreator.getAccountSession());%0A            Assert.assertEquals(quotaInventory.getValue(), snapshotNum.getTotal().longValue());%0A            Assert.assertEquals(1, snapshotNum.getUsed().longValue());%0A        %7D%0A%0A
         // c

add ut for snapshot quota check