// ApplyDeployment plan to server
func (c *ICSPClient) ApplyDeploymentJobs(buildplans []string, bpdata *OSDPersonalityDataV2, s Server) (jt *JobTask, err error) {

	var dj DeploymentJobs
	var bplans []OSDBuildPlan
	var servers []Server

	// lookup buildplan by name
	for _, buildPlan := range buildplans {
		match, _ := regexp.MatchString("^(/rest/)(.+)*", buildPlan)
		if match {
			bp, err := c.GetBuildPlanByUri(utils.NewNstring(buildPlan))

			if err != nil {
				return jt, err
			}
			bplans = append(bplans, bp)
		} else {
			bp, err := c.GetBuildPlanByName(buildPlan)
			if err != nil {
				return jt, err
			}
			bplans = append(bplans, bp)
		}
	}

	servers = append(servers, s)
	dj = dj.NewDeploymentJobs(bplans, bpdata, servers)
	jt, err = c.SubmitDeploymentJobs(dj)
	err = jt.Wait()
	if err != nil {
		return jt, err
	}
	return jt, nil
}
func (c *OVClient) DeleteOSBuildPlanFromServer(profileName string) error {
	s, err := c.GetProfileByName(profileName)
	if err != nil || s.URI.IsNil() {
		return fmt.Errorf("Server not found\n %+v", err)
	}

	blade, err := c.GetServerHardware(s.ServerHardwareURI)
	if err != nil {
		return err
	}

	err = blade.PowerOff()
	if err != nil {
		return err
	}

	s.OSDeploymentSettings.OSDeploymentPlanUri = utils.NewNstring("")
	//s.OSDeploymentSettings.OSCustomAttributes = nil

	err = c.UpdateServerProfile(s)
	if err != nil {
		return err
	}

	return nil
}
func TestCreateStorageVolume(t *testing.T) {
	var (
		d        *OVTest
		c        *OVClient
		testName string
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		d, c = getTestDriverA("test_storage_volume")
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		// find out if the test ethernet network already exist
		testName = d.Tc.GetTestData(d.Env, "Name").(string)

		testSVol, err := c.GetStorageVolumeByName(testName)
		assert.NoError(t, err, "CreateStorageVolume get the Storage Volume error -> %s", err)

		pMap := d.Tc.GetTestData(d.Env, "ProvisioningParameters").(map[string]interface{})

		provParams := ProvisioningParameters{StoragePoolUri: utils.NewNstring(pMap["storagePoolUri"].(string)), RequestedCapacity: pMap["requestedCapacity"].(string), ProvisionType: pMap["provisionType"].(string), Shareable: pMap["shareable"].(bool)}

		if testSVol.URI.IsNil() {
			testSVol = StorageVolumeV3{
				Name:             testName,
				StorageSystemUri: utils.NewNstring(d.Tc.GetTestData(d.Env, "StorageSystemUri").(string)),
				Type:             d.Tc.GetTestData(d.Env, "Type").(string),
				ProvisioningParameters: provParams,
			}

			// not changed after this TODO: update to storage volume tests
			err := c.CreateStorageVolume(testSVol)
			assert.NoError(t, err, "CreateStorageVolume error -> %s", err)

			err = c.CreateStorageVolume(testSVol)
			assert.Error(t, err, "CreateStorageVolume should error because the Storage volume already exists, err-> %s", err)

		} else {
			log.Warnf("The storage volume already exist, so skipping CreateStorageVolume test for %s", testName)
		}

		// reload the test profile that we just created
		testSVol, err = c.GetStorageVolumeByName(testName)
		assert.NoError(t, err, "GetStorageVolumeByName error -> %s", err)
	}

}
func TestCreateProfileTemplate(t *testing.T) {
	var (
		d        *OVTest
		c        *ov.OVClient
		testName string
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		d, c = getTestDriverA("test_server_profile_template")
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		// find out if the test Server Profile Template already exist
		testName = d.Tc.GetTestData(d.Env, "Name").(string)

		testServerProfileTemplate, err := c.GetProfileTemplateByName(testName)
		assert.NoError(t, err, "CreateServerProfileTemplate get the ServerProfileTemplate error -> %s", err)

		if testServerProfileTemplate.URI.IsNil() {
			testServerProfileTemplate = ov.ServerProfile{
				Name: testName,
				Type: d.Tc.GetTestData(d.Env, "Type").(string),
				ServerHardwareTypeURI: utils.NewNstring(d.Tc.GetTestData(d.Env, "ServerHardwareTypeUri").(string)),
				EnclosureGroupURI:     utils.NewNstring(d.Tc.GetTestData(d.Env, "EnclosureGroupUri").(string)),
			}

			err := c.CreateProfileTemplate(testServerProfileTemplate)
			assert.NoError(t, err, "CreateServerProfileTemplate error -> %s", err)

			//err = c.CreateProfileTemplate(testServerProfileTemplate)
			//assert.Error(t, err, "CreateServerProfileTemplate should error because the Server Profile Template already exists, err-> %s", err)

		} else {
			log.Warnf("The serverProfileTemplate already exist, so skipping CreateServerProfileTemplate test for %s", testName)
		}

		// reload the test profile that we just created
		testServerProfileTemplate, err = c.GetProfileTemplateByName(testName)
		assert.NoError(t, err, "GetServerProfileTemplate error -> %s", err)
	}
}
func TestCreateLogicalSwitchGroup(t *testing.T) {
	var (
		d        *OVTest
		c        *ov.OVClient
		testName string
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		d, c = getTestDriverA("test_logical_switch_group")
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		// find out if the test logicalSwitchGroup already exist
		testName = d.Tc.GetTestData(d.Env, "Name").(string)

		testLogicalSwitchGroup, err := c.GetLogicalSwitchGroupByName(testName)
		assert.NoError(t, err, "CreateLogicalSwitchGroup get the LogicalSwitchError error -> %s", err)

		if testLogicalSwitchGroup.URI.IsNil() {

			switchMapData := d.Tc.GetTestData(d.Env, "SwitchMapTemplate").(map[string]interface{})

			locationEntry := ov.LocationEntry{
				RelativeValue: 1,
				Type:          switchMapData["SwitchMapEntryTemplates"].([]interface{})[0].(map[string]interface{})["LogicalLocation"].(map[string]interface{})["LocationEntries"].([]interface{})[0].(map[string]interface{})["Type"].(string),
			}
			locationEntries := make([]ov.LocationEntry, 1)
			locationEntries[0] = locationEntry
			logicalLocation := ov.LogicalLocation{
				LocationEntries: locationEntries,
			}

			switchMapEntry := ov.SwitchMapEntry{
				PermittedSwitchTypeUri: utils.NewNstring(switchMapData["SwitchMapEntryTemplates"].([]interface{})[0].(map[string]interface{})["PermittedSwitchTypeUri"].(string)),
				LogicalLocation:        logicalLocation,
			}
			switchMapEntries := make([]ov.SwitchMapEntry, 1)
			switchMapEntries[0] = switchMapEntry

			switchMapTemplate := ov.SwitchMapTemplate{
				SwitchMapEntryTemplates: switchMapEntries,
			}
			//log.Warnf("%s", switchMapData["SwitchMapEntryTemplates"].([]interface{})[0].(map[string]interface{})["LogicalLocation"].(map[string]interface{})["LocationEntries"].([]interface{})[0].(map[string]interface{})["RelativeValue"])
			testLogicalSwitchGroup = ov.LogicalSwitchGroup{
				Name:              testName,
				Type:              d.Tc.GetTestData(d.Env, "Type").(string),
				Category:          d.Tc.GetTestData(d.Env, "Category").(string),
				SwitchMapTemplate: switchMapTemplate,
			}
			err := c.CreateLogicalSwitchGroup(testLogicalSwitchGroup)
			assert.NoError(t, err, "CreateLogicalSwitchGroup error -> %s", err)

			err = c.CreateLogicalSwitchGroup(testLogicalSwitchGroup)
			assert.Error(t, err, "CreateLogicalSwitchGroup should error because the LogicalSwitchGroup already exists, err-> %s", err)

		} else {
			log.Warnf("The logicalSwitchGroup already exists, so skipping CreateLogicalSwitchGroup test for %s", testName)
		}

		// reload the test profile that we just created
		testLogicalSwitchGroup, err = c.GetLogicalSwitchGroupByName(testName)
		assert.NoError(t, err, "GetLogicalSwitchGroupByName error -> %s", err)
	}

}
func TestCreateLogicalInterconnectGroup(t *testing.T) {
	var (
		d                *OVTest
		interconnectData *OVTest
		c                *OVClient
		testName         string
	)
	if os.Getenv("ONEVIEW_TEST_ACCEPTANCE") == "true" {
		d, c = getTestDriverA("test_logical_interconnect_group")
		if c == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}

		interconnectData, c = getTestDriverA("test_interconnect_type")
		if c == nil || interconnectData == nil {
			t.Fatalf("Failed to execute getTestDriver() ")
		}
		testName = d.Tc.GetTestData(d.Env, "Name").(string)
		testLogicalInterconnectGroup, err := c.GetLogicalInterconnectGroupByName(testName)
		assert.NoError(t, err, "CreateLogicalInterconnectGroup get the LogicalInterconnectError error -> %s", err)

		if testLogicalInterconnectGroup.URI.IsNil() {

			interconnectMapEntryTemplates := make([]InterconnectMapEntryTemplate, 8)
			for i := 0; i < 8; i++ {
				locationEntry1 := LocationEntry{
					RelativeValue: i + 1,
					Type:          "Bay",
				}
				locationEntry2 := LocationEntry{
					RelativeValue: i + 2,
					Type:          "Enclosure",
				}
				locationEntries := make([]LocationEntry, 2)
				locationEntries[0] = locationEntry1
				locationEntries[1] = locationEntry2
				logicalLocation := LogicalLocation{
					LocationEntries: locationEntries,
				}

				interconnectMapEntryTemplate := InterconnectMapEntryTemplate{
					LogicalLocation:              logicalLocation,
					PermittedInterconnectTypeUri: utils.NewNstring(interconnectData.Tc.GetTestData(interconnectData.Env, "URI").(string)),
				}
				interconnectMapEntryTemplates[i] = interconnectMapEntryTemplate
			}
			interconnectMapTemplate := InterconnectMapTemplate{
				InterconnectMapEntryTemplates: interconnectMapEntryTemplates,
			}

			f := false
			tr := true
			ethernetSettings := EthernetSettings{
				Type: "EthernetInterconnectSettingsV3",
				EnableFastMacCacheFailover: &f,
				EnableIgmpSnooping:         &tr,
				EnableRichTLV:              &tr,
				MacRefreshInterval:         10,
				IgmpIdleTimeoutInterval:    250,
			}

			telemetryConfig := TelemetryConfiguration{
				Type:            "telemetry-configuration",
				EnableTelemetry: &tr,
				SampleCount:     12,
				SampleInterval:  150,
			}

			snmpConfiguration := SnmpConfiguration{
				Type:          "snmp-configuration",
				Enabled:       &f,
				ReadCommunity: "test",
				SystemContact: "sys contact",
				SnmpAccess:    []string{"192.168.1.0/24"},
			}

			qosTrafficClassifiers := make([]QosTrafficClassifier, 4)
			qosTrafficClass := QosTrafficClass{
				BandwidthShare:   "10",
				EgressDot1pValue: 5,
				MaxBandwidth:     10,
				RealTime:         &tr,
				ClassName:        "RealTime",
				Enabled:          &tr,
			}
			qosClassificationMap1 := QosClassificationMap{
				Dot1pClassMapping: []int{5, 6, 7},
				DscpClassMapping:  []string{"DSCP 46, EF", "DSCP 40, CS5", "DSCP 48, CS6", "DSCP 56, CS7"},
			}
			qosTrafficClassifier := QosTrafficClassifier{
				QosTrafficClass:          qosTrafficClass,
				QosClassificationMapping: &qosClassificationMap1,
			}
			qosTrafficClassifiers[0] = qosTrafficClassifier

			qosTrafficClass = QosTrafficClass{
				BandwidthShare:   "fcoe",
				EgressDot1pValue: 3,
				MaxBandwidth:     100,
				RealTime:         &f,
				ClassName:        "FCoE lossless",
				Enabled:          &tr,
			}
			qosClassificationMap2 := QosClassificationMap{
				Dot1pClassMapping: []int{3},
				DscpClassMapping:  []string{},
			}
			qosTrafficClassifier = QosTrafficClassifier{
				QosTrafficClass:          qosTrafficClass,
				QosClassificationMapping: &qosClassificationMap2,
			}
			qosTrafficClassifiers[1] = qosTrafficClassifier

			qosTrafficClass = QosTrafficClass{
				BandwidthShare:   "65",
				EgressDot1pValue: 0,
				MaxBandwidth:     100,
				RealTime:         &f,
				ClassName:        "Best effort",
				Enabled:          &tr,
			}
			qosClassificationMap3 := QosClassificationMap{
				Dot1pClassMapping: []int{1, 0},
				DscpClassMapping:  []string{"DSCP 10, AF11", "DSCP 12, AF12", "DSCP 14, AF13", "DSCP 8, CS1", "DSCP 0, CS0"},
			}
			qosTrafficClassifier = QosTrafficClassifier{
				QosTrafficClass:          qosTrafficClass,
				QosClassificationMapping: &qosClassificationMap3,
			}
			qosTrafficClassifiers[2] = qosTrafficClassifier

			qosTrafficClass = QosTrafficClass{
				BandwidthShare:   "25",
				EgressDot1pValue: 2,
				MaxBandwidth:     100,
				RealTime:         &f,
				ClassName:        "Medium",
				Enabled:          &tr,
			}
			qosClassificationMap4 := QosClassificationMap{
				Dot1pClassMapping: []int{4, 3, 2},
				DscpClassMapping: []string{"DSCP 18, AF21",
					"DSCP 20, AF22",
					"DSCP 22, AF23",
					"DSCP 26, AF31",
					"DSCP 28, AF32",
					"DSCP 30, AF33",
					"DSCP 34, AF41",
					"DSCP 36, AF42",
					"DSCP 38, AF43",
					"DSCP 16, CS2",
					"DSCP 24, CS3",
					"DSCP 32, CS4"},
			}
			qosTrafficClassifier = QosTrafficClassifier{
				QosTrafficClass:          qosTrafficClass,
				QosClassificationMapping: &qosClassificationMap4,
			}
			qosTrafficClassifiers[3] = qosTrafficClassifier

			activeQosConfig := ActiveQosConfig{
				Type:                       "QosConfiguration",
				ConfigType:                 "CustomWithFCoE",
				QosTrafficClassifiers:      qosTrafficClassifiers,
				UplinkClassificationType:   "DOT1P",
				DownlinkClassificationType: "DOT1P_AND_DSCP",
			}

			qosConfiguration := QosConfiguration{
				Type:            "qos-aggregated-configuration",
				ActiveQosConfig: activeQosConfig,
			}

			testLogicalInterconnectGroup := LogicalInterconnectGroup{
				Name:                    testName,
				Type:                    d.Tc.GetTestData(d.Env, "Type").(string),
				EnclosureType:           d.Tc.GetTestData(d.Env, "EnclosureType").(string),
				InterconnectMapTemplate: &interconnectMapTemplate,
				EthernetSettings:        &ethernetSettings,
				TelemetryConfiguration:  &telemetryConfig,
				SnmpConfiguration:       &snmpConfiguration,
				QosConfiguration:        &qosConfiguration,
			}

			err := c.CreateLogicalInterconnectGroup(testLogicalInterconnectGroup)
			assert.NoError(t, err, "CreateLogicalInterconnectGroup error -> %s", err)

			err = c.CreateLogicalInterconnectGroup(testLogicalInterconnectGroup)
			assert.Error(t, err, "CreateLogicalInterconnectGroup should error because the LogicalInterconnectGroup already exists, err-")
		} else {
			log.Warnf("The logicalInterconnectGroup already exists, so skipping CreateLogicalInterconnectGroup test for %s", testName)
		}
	}

}