﻿using PaintTracker.Core.Models;
using PaintTracker.Core.ViewModels;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace PaintTracker.Core.Services
{
    public class UpdateService
    {
        private HtmlParser _parser;
        private ViewModelService _viewModelService;
        private DataCache _dataCache;
        private SettingsService _settingsService;
        private DialogService _dialogService;

        public UpdateService(HtmlParser parser, DialogService dialogService, ViewModelService viewModelService, DataCache dataCache, SettingsService settingsService)
        {
            _parser = parser;
            _viewModelService = viewModelService;
            _dataCache = dataCache;
            _settingsService = settingsService;
            _dialogService = dialogService;
        }

        public async Task TryUpdateAsync(bool hasExistingData, bool showDialog)
        {
            var currentDataVersion = _settingsService.DataVersion;
            var updateResponse = await _parser.CheckForUpdate(currentDataVersion);
            var hasNewData = false;

            if (updateResponse.Success)
            {
                var data = await _parser.GetPaintDataAsync();
                if (data.Success)
                {
                    if (hasExistingData && showDialog)
                    {
                        _dialogService.ShowProgressDialog("Updating", "Updating paint data...");
                        // TODO: prevent import/export during this.
                    }
                    else if (!hasExistingData)
                    {
                        await _dataCache.InitialiseAsync();
                    }

                    hasNewData = true;
                    await _dataCache.SaveDataAsync(data.Data);
                    _settingsService.DataVersion = updateResponse.DataVersion;
                    _settingsService.ApiVersion = updateResponse.ApiVersion;
                }
            }

            if (hasNewData)
            {
                if (hasExistingData && showDialog)
                {
                    MessagingCenter.Send(this, Messages.NewPaintData);
                    _dialogService.HideProgressDialog();
                }
                else if (!hasExistingData)
                {
                    await _viewModelService.ShowMasterDetailPageForVMAsync<PaintsVM, PaintGroupVM>();
                }
            }
            else
            {
                if (!hasExistingData)
                {
                    await _viewModelService.ShowPageForVMAsync<ErrorVM, ErrorVMArgs>(new ErrorVMArgs(updateResponse.ErrorMessage, updateResponse.Troubleshooting, updateResponse != HtmlUpdateResult.UnsupportedApiVersion));
                }
            }
        }
    }
}
