using Abp.Domain.Repositories;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;
using YGNT.Infrastructure.Helper;
using YGNT.Infrastructure.Model;
using YGNT.QuestionLibrary.Core.Courses;
using YGNT.QuestionLibrary.Courses.Dto;

namespace YGNT.QuestionLibrary.Courses
{
    /// <summary>
    /// 課程
    /// </summary>
    public class CoursesAppService: ICoursesAppService
    {
        private readonly IRepository<Course> _courseRepository;
        private readonly IHttpHelper _httpHelper;

        public CoursesAppService(IRepository<Course> courseRepository, IHttpHelper httpHelper)
        {
            _courseRepository = courseRepository;
            _httpHelper = httpHelper;
        }

        /// <summary>
        /// 課程
        /// </summary>
        /// <returns></returns>
        public async Task<List<Course>> GetListAll()
        {
            return await _courseRepository.GetAll().ToListAsync();
        }

        /// <summary>
        /// 同步課程
        /// </summary>
        /// <returns></returns>
        public async Task DataSyncAsync()
        {

            HttpResult httpResult = await _httpHelper.GetResponse($"{AppSettings.App("App", "ServerRoot")}/api/magic-api/educational/abutment/course-subject-info");
            if (httpResult.Success)
            {
                var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CourseSyncDto>>(httpResult.Data.ToString());

                foreach (var item in list)
                {
                    var isExist = await _courseRepository.GetAll().AnyAsync(x => x.SourceId == item.Id);
                    if (isExist)
                    {
                        var course = await _courseRepository.FirstOrDefaultAsync(i => i.SourceId == item.Id);
                        course.Name = item.Name;
                        await _courseRepository.UpdateAsync(course);
                    }
                    else
                    {
                        var course = new Course { Name = item.Name, SourceId = item.Id };

                        await _courseRepository.InsertAndGetIdAsync(course);

                    }
                }
            }
            else
            {
                throw new UserFriendlyException(httpResult.Message);
            }
        }
    }
}
