using ManagementPage.Auth;
using ManagementPage.Database;
using ManagementPage.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Security.Claims;

namespace ManagementPage.Pages
{

    [Authorize]
    public class UserHomeModel : PageModel
    {
        public List<DeviceData> data;
        public Dictionary<Int64, EnvironmentData> currentEnvironment;
        public string name;

        private readonly MongoDbClient _dbClient;

        public class NewDeviceModel
        {
            public string Name { get; set; }
            public string Passcode { get; set; }
        }

        [BindProperty]
        public NewDeviceModel NewDevice { get; set; }

        public UserHomeModel(MongoDbClient dbClient)
        {
            data = new List<DeviceData>();
            currentEnvironment = new Dictionary<Int64, EnvironmentData>();
            _dbClient = dbClient;
            NewDevice = new NewDeviceModel();
        }

        public async Task OnGetAsync()
        {
            var binder = new AccountBinder(_dbClient);

            var id = await binder.GetLocalAccount(User.FindFirstValue(ClaimTypes.NameIdentifier));
            name = User.FindFirstValue(ClaimTypes.GivenName);

            using var cursor = await _dbClient.DeviceCollection.FindAsync(new BsonDocument());
            data = cursor.ToList();


            foreach (var item in data)
            {
                var filter = new BsonDocument("ApiID", item.ApiID);
                var envData = await _dbClient.Collection.Find(filter).SortByDescending(x => x.Time).FirstOrDefaultAsync();
                envData ??= new EnvironmentData(item.ApiID, 0, 0, DateTime.UtcNow);
                currentEnvironment.Add(item.ApiID, envData);
            }
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            var id = BitConverter.ToInt64(Guid.NewGuid().ToByteArray(),4);
            var device = new DeviceData(NewDevice.Name, NewDevice.Passcode, id);
            device._id = ObjectId.GenerateNewId();
            await _dbClient.DeviceCollection.InsertOneAsync(device);

            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var filter = new BsonDocument("OpenId", userId);
            var update = Builders<UserData>.Update.AddToSet("Devices", device._id);

            await _dbClient.AccountsCollection.UpdateOneAsync(filter, update);
            return new RedirectToPageResult("/UserHome");
        }
    }
}
