using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Storage;

namespace GhostArena5
{
    [Serializable]
    public class HighScore
    {
        public string Date;
        public int Level;
        public int Score;

        public HighScore()
        {

        }

        public HighScore(string date, int level, int score)
        {
            Date = date;
            Level = level;
            Score = score;
        }
    }

    public class HighScoreList
    {
        private List<HighScore> _scores;

        private StorageContainer _container;

        public List<HighScore> Scores
        {
            get {return _scores;}
        }

        public HighScoreList()
        {
            Object obj = (Object)"GetDevice for Player One";
            Guide.BeginShowStorageDeviceSelector(StorageDeviceSelected, obj);
        }

        private void StorageDeviceSelected(IAsyncResult result)
        {
            StorageDevice device = Guide.EndShowStorageDeviceSelector(result);

            if (device.IsConnected)
            {
                _container = device.OpenContainer("Ghost Arena 4");

                if (File.Exists(_container.Path + "\\scores.xml"))
                {
                    //open the file here
                    FileStream stream = File.Open(_container.Path + "\\scores.xml", FileMode.OpenOrCreate);
                    Load(stream);

                    stream.Close();
                }
            }
        }

        public void Save()
        {
            FileStream stream = File.Open(_container.Path + "\\scores.xml", FileMode.OpenOrCreate);
            Save(stream);

            stream.Close();
        }

        public void Save(FileStream stream)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<HighScore>));
            serializer.Serialize(stream, _scores);
        }

        public void Load(FileStream stream)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<HighScore>));
            _scores = (List<HighScore>)serializer.Deserialize(stream);
        }

        public void AddScore(HighScore score)
        {
            if (_scores == null)
                _scores = new List<HighScore>();

            bool scoreAdded = false;

            for (int i = 0; i < _scores.Count; i++)
            {
                if (_scores[i].Score < score.Score)
                {
                    _scores.Insert(i, score);
                    scoreAdded = true;

                    if (_scores.Count > 10)
                        _scores.RemoveAt(10);

                    break;
                }
            }

            if (!scoreAdded && _scores.Count < 10)
                _scores.Add(score);
        }
    }
}
