using inutralia.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace inutralia.ViewModels
{
    public class TrivialGameViewModel : BaseNavigationViewModel
    {
        public class QuestionResult
        {
            public TrivialQuestion Question { get; set; }

            public string ValidAnswer => Question.Options [Question.ValidIndex];

            public string Answer => Question.Options [SelectedAnswer];

            public int SelectedAnswer { get; set; }

            public bool IsCorrect { get; set; }

            public bool IsNotCorrect => !IsCorrect;
        }

        public TrivialGame Game { get; private set; }

        public List<QuestionResult> Results { get; private set; }

        public bool IsComplete => 
            (Game?.Questions?.Count > 0) && 
            (Game?.Questions?.Count == Game?.Answers?.Count);

        public bool IsNotComplete => !IsComplete;

        public TrivialQuestion CurrentQuestion
        {
            get
            {
                int n = Game.Answers.Count;
                return (n >= 0) && (n < Game.Questions.Count) ? Game.Questions [n] : null;
            }
        }

        public TrivialGameViewModel ( TrivialGame game)
        {
            Game = game;
            Results = null;
            GenerateTitle ();
            GenerateResults ();
        }

        public async Task<bool> Answer ( int answer)
        {
            bool retVal = Game.Answer (answer);

            await App.LocalData.UpdateItemAsync (Game);

            GenerateTitle ();
            GenerateResults ();
            OnPropertyChanged ("CurrentQuestion");
            OnPropertyChanged ("IsComplete");
            OnPropertyChanged ("IsNotComplete");

            return retVal;
        }

        protected void GenerateResults ()
        {
            if(IsComplete)
            {
                if(Results == null)
                {
                    Results = new List<QuestionResult> ();
                    for(int i = 0; i < Game.Questions.Count; i++)
                    {
                        TrivialQuestion q = Game.Questions [i];
                        int answer = Game.Answers [i];
                        Results.Add (new QuestionResult ()
                        {
                            Question = q,
                            SelectedAnswer = answer,
                            IsCorrect = (q.ValidIndex == answer)
                        });
                    } //endfor

                    OnPropertyChanged ("Results");
                } //endif
            } //endif
        }

        protected void GenerateTitle ()
        {
            if(IsComplete)
            {
                Title = "Trivial: Partida completada";
            }
            else
            {
                Title = $"Trivial: Pregunta {Game.Answers.Count + 1} de {Game.Questions.Count}";
            } //endif
        }

    }
}
