namespace inutralia.Models
{
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;

    [JsonObject(MemberSerialization.OptIn)]
    [DataPath("game")]

    public class TrivialGame : ObservableEntityData
    {
        [JsonProperty("start", Required = Required.Always)]
        public string StartDate { get; protected set; }

        [JsonProperty("finish", Required = Required.Always)]
        public string FinishDate { get; protected set; }

        [JsonProperty("questions", Required = Required.Always)]
        public IList<TrivialQuestion> Questions;

        [JsonProperty("answers", Required = Required.Always)]
        public IList<int> Answers;

        public string Progress => $"{Answers.Count} / {Questions.Count}";

        public string Score
        {
            get
            {
                // Si no está todo respondido, no hay puntuación
                int n = Answers.Count;
                if ((n < Questions.Count) || (n < 1))
                    return "";

                // Calcular respuestas correctas
                int correctas = 0;
                for (int i = 0; i < n; i++)
                    if (Questions[i].ValidIndex == Answers[i])
                        correctas++;

                // TODO: Otro mecanismo de score ?
                int score = (100 * correctas) / n;
                return score.ToString();
            }
        }

        public static TrivialGame Create(IList<TrivialQuestion> questions)
        {
            TrivialGame game = new TrivialGame();
            game.Questions = questions;
            game.Answers = new List<int>();
            game.StartDate = DateTime.Now.ToString();
            game.FinishDate = "";
            return game;
        }

        public bool Answer(int answer)
        {
            int n = Answers.Count;
            if (n < Questions.Count)
            {
                Answers.Add(answer);
                OnPropertyChanged("Answers");
                OnPropertyChanged("Progress");
                OnPropertyChanged("Score");
                return Questions[n].ValidIndex == answer;
            } //endif

            return false;
        }
    }
}
