using JtkMainServer.ApiModels;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JtkMainServer.Managers {
    /// <summary>
    /// JTK PC방 메인 서버에 종속적으로 설계된 DB 관리용 정적 클래스입니다.
    /// </summary>
    public static class PlaceManager {
        private readonly static Dictionary<string, int[]> usingPcNumbers = new Dictionary<string, int[]>();
        private readonly static Dictionary<string, int> totalPcCounts = new Dictionary<string, int>();
        private readonly static Dictionary<string, double> farePerHours = new Dictionary<string, double>();

        public static void UpdateUsingPcNumbers(string placeId, int totalPcCount, List<int> numbers) {
            UpdateUsingPcNumbers(placeId, totalPcCount, numbers.ToArray());
        }

        public static void UpdateUsingPcNumbers(string placeId, int totalPcCount, int[] numbers) {
            var sorted = from num in numbers orderby num ascending select num;
            lock (totalPcCounts) { totalPcCounts[placeId] = totalPcCount; }
            lock (usingPcNumbers) { usingPcNumbers[placeId] = sorted.ToArray(); }
        }

        public static void UpdateFarePerHour(string placeId, double farePerHour) {
            lock (farePerHours) {
                farePerHours[placeId] = farePerHour;
            }
        }

        public static int[] GetUsingPcNumbers(string placeId) {
            lock (usingPcNumbers) {
                return usingPcNumbers.ContainsKey(placeId) ? usingPcNumbers[placeId] : null;
            }
        }

        public static int GetTotalPcCount(string placeId) {
            lock (totalPcCounts) {
                return totalPcCounts.ContainsKey(placeId) ? totalPcCounts[placeId] : -1;
            }
        }

        public static double GetFarePerHour(string placeId) {
            lock (farePerHours) {
                return farePerHours.ContainsKey(placeId) ? farePerHours[placeId] : -1;
            }
        }

        public static (string id, string name, int totalPcCount, int remainingPcCount, string location)[] GetAllPlaces() {
            var result = new List<(string id, string name, int totalPcCount, int remainingPcCount, string location)>();
            var dbList = DbManager.GetAllPlaces();
            foreach (var place in dbList) {
                var totalPcCount = GetTotalPcCount(place.Id);
                var usingPcCount = GetUsingPcNumbers(place.Id)?.Length ?? -1;
                result.Add((place.Id, place.Name, totalPcCount, totalPcCount - usingPcCount, place.Location));
            }
            return result.ToArray();
        }
    }
}
