using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Qusion.Cms.Media.Core;
using Qusion.Cms.Web.Http;

namespace Qusion.WebApp.Areas.Qusion.Controllers.Api
{
    public class UploadController : ApiController
    {
        private readonly DocumentService _documentService;
        private readonly ImageService _imageService;
        private readonly LibraryService _libraryService;

        public UploadController(LibraryService libraryService, ImageService imageService,
                                DocumentService documentService)
        {
            _libraryService = libraryService;
            _imageService = imageService;
            _documentService = documentService;
        }

        public Task<HttpResponseMessage> Upload(Guid? libraryId = null)
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            // todo : ovo je privremena putanja
            var root = @"D:\Apps\Qusion5\src\Qusion.WebApp\_content\";
            var provider = new CmsMultipartFormDataStreamProvider(root);

            // Read the form data and return an async task.
            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(t =>
                                 {
                                     if (t.IsFaulted || t.IsCanceled)
                                     {
                                         return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                                                                            t.Exception);
                                     }

                                     // todo: ovo je samo privremen nacin punjenja podataka
                                     // todo: provjeri da li library id postoji.
                                     var libid = new Guid(provider.FormData.Get("libraryId"));
                                     // todo: sada uzmi library prema id
                                     foreach (var file in provider.FileData)
                                     {
                                         //var name = file.LocalFileName;
                                         //// ovdje upisujemo
                                     }
                                     return Request.CreateResponse(HttpStatusCode.OK);
                                 });

            return task;
        }
    }
}