using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace VectorRace_LevelDesigner
{
    public class Level
    {
        public static readonly int WidthSegments = 10;
        public static readonly int HeightSegments = 10;
        public int[,] Fields;

        public Level()
        {
            Fields = new int[WidthSegments, HeightSegments];
        }

        public Level(int[,] fields)
        {
            Fields = fields;
        }

        public static Level Load(string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
            BinaryFormatter bf = new BinaryFormatter();

            int[,] array = (int[,])bf.Deserialize(fs);
            fs.Close();

            Level level = new Level(array);

            level = ReverseLevel(level);

            return level;
        }

        public static void Save(string filename, Level level)
        {
            level = ReverseLevel(level);
            FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, level.Fields);
            fs.Close();
        }

        private static Level ReverseLevel(Level level)
        {
            int[,] reversed = new int[WidthSegments, HeightSegments];

            for (int i = 0; i < WidthSegments; i++)
            {
                for (int j = 0; j < HeightSegments; j++)
                {
                    reversed[i, j] = level.Fields[(WidthSegments - 1) - i, (HeightSegments - 1) - j];
                }
            }

            level.Fields = reversed;

            return level;
        }
    }
}