using Microsoft.Xna.Framework.Input;

namespace Game200
{
    public class LevelEditor
    {
        Vec dim, coord;
        Segment[,] x, y;
        bool isDrawing;
        float curTime, maxTime;

        public LevelEditor(int dimX, int dimY)
        {
            dim = new Vec(dimX, dimY);
            isDrawing = false;
            curTime = 0;
            maxTime = 0.05f;
            x = new Segment[dim.X, dim.Y];
            y = new Segment[dim.X, dim.Y];
            for (int i = 0; i < dim.X; i++)
                for (int j = 0; j < dim.Y; j++)
                {
                    x[i, j] = new Segment(i, j, true, false);
                    y[i, j] = new Segment(i, j, false, false);
                }
        }
        
        public void Update(float elapsed)
        {
            curTime += elapsed;
            KeyboardState keyState = Keyboard.GetState();
            if (isDrawing)
            {
                if (curTime > maxTime && keyState.IsKeyDown(Keys.Up) && coord.X > 0)
                {
                    curTime = 0;
                    y[coord.X - 1, coord.Y].EditorUpd();
                    coord.X--;
                }
                if (curTime > maxTime && keyState.IsKeyDown(Keys.Down) && coord.X < dim.X - 1)
                {
                    curTime = 0;
                    y[coord.X, coord.Y].EditorUpd();
                    coord.X++;
                }
                if (curTime > maxTime && keyState.IsKeyDown(Keys.Left) && coord.Y > 0)
                {
                    curTime = 0;
                    x[coord.X, coord.Y - 1].EditorUpd();
                    coord.Y--;
                }
                if (curTime > maxTime && keyState.IsKeyDown(Keys.Right) && coord.Y < dim.Y - 1)
                {
                    curTime = 0;
                    x[coord.X, coord.Y].EditorUpd();
                    coord.Y++;
                }
                if (C.IsMouseReleased())
                    isDrawing = false;
            }
            else
            {
                coord = C.MousePos();
                if (C.IsMousePressed() && coord.X >= 0 && coord.X < dim.X && coord.Y >= 0 && coord.Y < dim.Y)
                    isDrawing = true;
            }
        }

        public void Export(Map map)
        {
            map.dim = dim;
            map.x = new Segment[dim.X, dim.Y];
            map.y = new Segment[dim.X, dim.Y];
            for (int i = 0; i < dim.X; i++)
                for (int j = 0; j < dim.Y; j++)
                {
                    map.x[i, j] = x[i, j];
                    map.y[i, j] = y[i, j];
                }
            map.SetColorData();
        }

        public void Draw()
        {
            foreach (Segment s in x)
                s.EditorDraw();
            foreach (Segment s in y)
                s.EditorDraw();
        }
    }
}
