﻿using System;
using System.Data;
using System.Globalization;
using System.Linq;
using WarframeDropRatesDataParser;
using WarframeDropRatesDataParser.DropTables;

namespace WarframeDropRatesData.Models.Repositories
{
    /// <summary>
    /// </summary>
    internal sealed class SortieRewardsRepository : Repository, ISortieRewardsRepository
    {
        private readonly SortieRewardsDropTable[] _sortieRewards;

        /// <summary>
        /// </summary>
        /// <param name="data"></param>
        public SortieRewardsRepository(DropRatesRawData data) : base(data)
        {
            _sortieRewards = DropRatesRawData.SortieRewards;
        }

        /// <summary>
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool IsSortie(string name)
        {
            return _sortieRewards.Any(
                r => r.Sortie.Equals(name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// </summary>
        /// <returns></returns>
        public string[] GetAllSortieNames()
        {
            return _sortieRewards.Select(r => r.Sortie).ToArray();
        }

        /// <summary>
        /// </summary>
        /// <param name="sortieName"></param>
        /// <returns></returns>
        public DataTable GetRewardsBySortie(string sortieName)
        {
            foreach (var sortieReward in _sortieRewards)
            {
                if (sortieReward.Sortie.Equals(sortieName, StringComparison.OrdinalIgnoreCase))
                {
                    var dataTable = CreateDataTable(sortieReward.TableName);

                    foreach (var item in sortieReward.Items)
                    {
                        var dataRow = dataTable.NewRow();
                        dataRow[ItemColumnName] = item.Name;
                        dataRow[RarityColumnName] = item.Rarity;
                        dataRow[DropChanceColumnName] = item.DropChance;
                        dataTable.Rows.Add(dataRow);
                    }

                    return dataTable;
                }
            }

            return null;
        }

        private static DataTable CreateDataTable(string tableName)
        {
            var dataTable = new DataTable
            {
                TableName = tableName,
                Locale = CultureInfo.InvariantCulture,
                CaseSensitive = false
            };

            dataTable.Columns.Add(new DataColumn(ItemColumnName, typeof(string))
            {
                AllowDBNull = false
            });

            dataTable.Columns.Add(new DataColumn(RarityColumnName, typeof(string))
            {
                AllowDBNull = false
            });

            dataTable.Columns.Add(new DataColumn(DropChanceColumnName, typeof(double))
            {
                AllowDBNull = false
            });

            return dataTable;
        }
    }
}