using Otter;
using System;
using System.Collections.Generic;

namespace SuperRefluxPowergridDefense_.entities
{
    class Grid : Entity
    {
        private Spritemap<string> _spriteMap;
        private bool isPowerChanged = true;
        private bool isBatteryChanged = true;
        public int GridHealth = 1000;

        public Grid(float x, float y)
        {
            X = x; Y = y;
            SetHitbox(180, 60, (int)Global.Type.GRID);
            Collider.X = -90;
            Collider.Y = -15;
            _spriteMap = new Spritemap<string>(Assets.GRID, 200, 100);
            _spriteMap.Add("main", new int[] { 0 }, new float[] { 10f, 10f });
            _spriteMap.Play("main");
            Graphic = _spriteMap;
            _spriteMap.CenterOrigin();
        }

        public override void Update()
        {
            base.Update();
            if (Global.TotalGlobalPower >= Global.MaxPowerOutput)
                Global.TotalGlobalPower = Global.MaxPowerOutput;
            if (Global.Battery < Global.MaxBattery && Global.TotalGlobalPower >= 100)
            {
                //Console.WriteLine("WE RE CHARGING THE BATTERY.");
                Global.TotalGlobalPower -= 100;
                Global.Battery += 100;
            }
            var _divisor = Global.TotalGlobalPower / 100;
            var _batteryDivisor = Global.Battery / 100;
            //Console.WriteLine("divisor {0}", (int)_divisor);
            //Console.WriteLine("batterydivisor {0}", (int)_batteryDivisor);
            if (Global.currentDivisor > (int)_divisor || Global.currentDivisor < (int)_divisor)
                isPowerChanged = true;
            if (Global.batteryDivisor > (int)_batteryDivisor || Global.batteryDivisor < (int)_batteryDivisor)
                isBatteryChanged = true;
            if (isPowerChanged)
            {
                //Console.WriteLine("power changed {0}", isPowerChanged);
                isPowerChanged = false;
                Global.currentDivisor = (int)_divisor;
            }

            if (isBatteryChanged)
            {
                //Console.WriteLine("battery changed {0}", isBatteryChanged);
                isBatteryChanged = false;
                Global.batteryDivisor = (int)_batteryDivisor;
            }
            //Take the total power generated, and put in a battery.
        }

        public override void Render()
        {
            base.Render();
            //Collider.Render();
        }

        public void Destroy()
        {
            RemoveSelf();
            Scene.Add(new PlayerDeath(X, Y));
            Global.TotalGlobalPower = 0;
            Global.Battery = 0;
            var powerCell = GetEntities<PowerCell>();
            foreach(var item in powerCell)
            {
                item.Destroy();
            }
            var batteryCell = GetEntities<BatteryCell>();
            foreach (var item in batteryCell)
            {
                item.Destroy();
            }
        }
    }
}