using Microsoft.Azure.Cosmos; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using TEAMModelOS.SDK.DI; using TEAMModelOS.SDK.Models; namespace TEAMModelOS.SDK { public class TmdUserService { public static async Task JoinSchool(CosmosClient client, string tmdid, string picture, string name, string schoolId, string schoolName) { TmdUser tmdUser = null; try { tmdUser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync(tmdid, partitionKey: new PartitionKey("Base")); tmdUser.picture = string.IsNullOrEmpty(picture) ? picture : tmdUser.picture; tmdUser.name = string.IsNullOrEmpty(name) ? name : tmdUser.name; var school = tmdUser.schools.Find(x => x.schoolId.Equals(schoolId)); if (school == null) { tmdUser.pk="Base"; tmdUser.schools.Add(new TmdUser.School { schoolId = schoolId, name = schoolName, status = "join", time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }); await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(tmdUser, tmdid, partitionKey: new PartitionKey("Base")); } else { tmdUser.pk="Base"; school.name = schoolName; await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(tmdUser, tmdid, partitionKey: new PartitionKey("Base")); } } catch (CosmosException ex) { if (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { tmdUser = new TmdUser() { createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), id = tmdid, code = "Base", pk="Base", schools = new List() { new TmdUser.School { schoolId = schoolId, status = "join", name = schoolName, time = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() } }, defaultSchool = schoolId, picture = picture, name = name, ttl = -1 }; await client.GetContainer(Constant.TEAMModelOS, "Student").CreateItemAsync(tmdUser, partitionKey: new PartitionKey(tmdUser.code)); } } return tmdUser; } public static async Task LeaveSchool(CosmosClient client, string tmdid, string schoolId) { TmdUser tmdUser = await client.GetContainer(Constant.TEAMModelOS, "Student").ReadItemAsync(tmdid, partitionKey: new PartitionKey("Base")); var school = tmdUser.schools.Find(x => x.schoolId.Equals(schoolId)); if (school != null) { tmdUser.schools.Remove(school); tmdUser.pk="Base"; await client.GetContainer(Constant.TEAMModelOS, "Student").ReplaceItemAsync(tmdUser, tmdid, partitionKey: new PartitionKey("Base")); } return tmdUser; } } }