using System;
using System.Collections.Generic;
using System.Text;
using Vortex.Drawing;

namespace Vortex.Tutorials.ParallaxEffect {

    public class Parallax {
        internal class ParallaxLayer {
            internal List<Sprite> Sprites;
            internal float Damping;

            internal ParallaxLayer(float damping) {
                Sprites = new List<Sprite>();
                this.Damping = damping;
            }

            internal void AddSprite(Sprite spr) {
                Sprites.Add(spr);
            }

            internal void RemoveSprite(Sprite spr) {
                Sprites.Remove(spr);
            }
        }

        private List<ParallaxLayer> layers;

        public Parallax() {
            layers = new List<ParallaxLayer>();

        }

        public void AddLayer() {
            AddLayer(1.0f);
        }

        public void AddLayer(float damping) {
            layers.Add(new ParallaxLayer(damping));
        }

        public void AddLayer(Sprite spr) {
            AddLayer(spr, 1.0f);
        }

        public void AddLayer(Sprite spr, float damping) {
            var layer = new ParallaxLayer(damping);
            layer.AddSprite(spr);
            layers.Add(layer);
        }

        public void InsertSprite(Sprite spr, int layerNum) {
            if (layerNum >= layers.Count) {
                layerNum -= 1;
            }
            layers[layerNum].AddSprite(spr);
        }

        public void RemoveSprite(Sprite spr) {
            foreach (var parallaxLayer in layers) {
                if (!parallaxLayer.Sprites.Contains(spr)) continue;

                parallaxLayer.RemoveSprite(spr);
                break;
            }
        }

        public void Render(Canvas2D canvas, Vector2 camPos) {
            foreach (var parallaxLayer in layers) {
                using (canvas <= new Translation(-camPos.X * parallaxLayer.Damping, -camPos.Y * parallaxLayer.Damping)) {
                    foreach (var sprite in parallaxLayer.Sprites) {
                        canvas.DrawSprite(canvas.Size / 2, sprite, ColorU.White);
                    }
                }
            }
        }
    }
}
