using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CafeTerrace.Models;
using CafeTerrace.Models.DataBase;
using CafeTerrace.Services;
using RestSharp;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace CafeTerrace.Views.DialogBox
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class AddCommentDialogBox : ContentView
    {
        private readonly Food _food;
        private int _starCount;
        public int StarCount
        {
            get { return _starCount; }
            set
            {
                _starCount = 0;
                for (int i = 0; i < value; i++)
                {
                    (starsStack.Children[i] as Label).TextColor = (Color)Application.Current.Resources["Gray-300"];
                }

                for (int i = starsStack.Children.Count-1 ; i >= value - 1; i--)
                {
                     (starsStack.Children[i] as Label).TextColor = (Color)Application.Current.Resources["PrimaryColor"];
                     _starCount++;
                }
            }
        }

        public AddCommentDialogBox(Food food)
        {
            _food = food;
            InitializeComponent();
        }

        private void StarLabel_OnTapped(object sender, EventArgs e)
        {
            StarCount = int.Parse((sender as Label).ClassId);
            
        }

        private async void SubmitButton_OnClicked(object sender, EventArgs e)
        {
            try
            {
                PopupNavigation.Instance.PushAsync(Utilities.PopUpUtilites.IndicatorPage);
                RestService<string> addCommentRestService = new RestService<string>(Address.BaseAddress);
                var rate = new Rate
                {
                    FoodId = _food.FoodId,
                    UserId = Utilities.Instance.LoginedUser.UserId,
                    Description = commentEditor.Text,
                    Point = _starCount
                };
                var res =await addCommentRestService.RequestBody(Address.AddComment, Method.POST, rate, true);
                if (res.IsSuccess)
                {
                    PopupNavigation.Instance.PopAllAsync();
                    PopupNavigation.Instance.PushAsync(Utilities.PopUpUtilites.SeccussPage("ثبت نظر شما با موفقیت انجام شد"));
                }
            }
            catch (Exception exception)
            {
                PopupNavigation.Instance.PopAllAsync();
                PopupNavigation.Instance.PushAsync(Utilities.PopUpUtilites.ErrorPage(exception.Message));
            }
        }
    }
}