using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;
using RevitEstimate.Models;

namespace RevitEstimate.Calculators
{
    public class Item46Calculator : IItemCalculator
    {
        private ProjectLevels _levels;
        public Item46Calculator(ProjectLevels levels = null) => _levels = levels ?? new ProjectLevels();

        public List<EstimateRowModel> Calculate(List<Element> collector, out double totalQty)
        {
            totalQty = 0.0;
            var rows = new List<EstimateRowModel>();
            var windows = collector.Where(e => e is FamilyInstance && e.Category != null && e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Windows).Cast<FamilyInstance>().ToList();

            foreach (var win in windows)
            {
                Parameter wParam = win.LookupParameter("Width") ?? (win.Symbol != null ? win.Symbol.LookupParameter("Width") : null);
                Parameter hParam = win.LookupParameter("Height") ?? (win.Symbol != null ? win.Symbol.LookupParameter("Height") : null);
                double w = wParam != null && wParam.HasValue ? UnitUtils.ConvertFromInternalUnits(wParam.AsDouble(), UnitTypeId.Meters) : 1.0;
                double h = hParam != null && hParam.HasValue ? UnitUtils.ConvertFromInternalUnits(hParam.AsDouble(), UnitTypeId.Meters) : 1.2;
                double area = w * h;
                totalQty += area;

                rows.Add(new EstimateRowModel
                {
                    SNo = "",
                    ItemOfWork = $"   -> M.S. Grill for Window: {win.Name} [ID: {win.Id}]",
                    NosOfFlats = "1",
                    NosOfInstance = "1",
                    Length = w.ToString("F2"),
                    Width = "",
                    HeightDepth = h.ToString("F2"),
                    Qty = area.ToString("F2"),
                    Unit = "Sqm",
                    Remarks = $"Window grill area ({w:F2}m x {h:F2}m)."
                });
            }
            if (rows.Count == 0) rows.Add(new EstimateRowModel { SNo = "", ItemOfWork = "   -> [No Windows found for Grills]", Qty = "0.00", Unit = "Sqm" });
            return rows;
        }
    }
}