using Blueprinter.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blueprinter.Presentation
{
    public class ViewMainPresenter : IViewMainPresenter
    {
        private readonly IViewMain _view;
        private readonly IApplicationController _appController;
        public ViewMainPresenter(IViewMain view, IApplicationController appController)
        {
            _view = view;
            _appController = appController;
            _view.Presenter = this;

            _appController.Context.BlueprintsUpdated += Context_BlueprintsUpdated;
            _appController.FileSaveAsResult +=_appController_FileSaveAsResult;
        }

        void _appController_FileSaveAsResult(object sender, string e)
        {
            var text = _view.ProjectBlueprint;

            var bp = new BlueprintInfo
            {
                Name = e,
                Blueprint = text
            };

            _appController.Context.SaveBlueprint(bp);
        }

        void Context_BlueprintsUpdated(object sender, EventArgs e)
        {
            _view.Blueprints = _appController.Context.GetAllBlueprints();
        }

        public IViewMain View
        {
            get
            {
                return _view;
            }
        }

        public void Run()
        {
            Context_BlueprintsUpdated(null, null);
            _view.Run();
        }

        public void RunBlueprintManager()
        {
            _appController.RunBlueprintManager();
        }

        public void RunTemplateManager()
        {
            _appController.RunTemplateManager();
        }


        public void SaveBlueprint()
        {
            var bp = _view.SelectedBlueprint;

            if (bp == null)
            {
                SaveBlueprintAs();
                return;
            }

            var text = _view.ProjectBlueprint;

            bp.Blueprint = text;

            _appController.Context.SaveBlueprint(bp);
        }

        public void SaveBlueprintAs()
        {
            _appController.RunFileSaveAs();
        }


        public void ExecuteBuild()
        {
            var path = _view.ProjectPath;
            var blueprintText = _view.ProjectBlueprint;

            var blueprint = BlueprintParser.Parse(blueprintText);
            var writer = _appController.Context.CreateNodeWriter(path);

            writer.WriteAsync(blueprint).ContinueWith(t => _view.DisplayMessage("Build complete"));
        }
    }
}
