using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using edu.jhu.Cas.Web;
using edu.jhu.Cas.Users;
using edu.jhu.Cas.Jobs;
using System.IO;
using net.ivoa.data;
using RestApi.Exceptions;
using SciServer.Logging;
using System.Web;

namespace RestApi.Controllers
{
    public class TablesController : ApiController
    {
        [ExceptionHandle]
        public HttpResponseMessage Post(string context_id, string table_id)
        {
            Logger log = (HttpContext.Current.ApplicationInstance as MvcApplication).Log;

            IEnumerable<string> values;
            string userid = null;

            if (ControllerContext.Request.Headers.TryGetValues("X-Auth-Token", out values))
            {
                long? wsid;

                try
                {
                    string token = values.First();
                    var userAccess = Keystone.Authenticate(token);
                    userid = userAccess.User.Id;

                    wsid = Keystone.GetWebServicesId(userAccess.User.Id);
                    if (wsid == null) throw new Exception("CasJobs user with the given Keystone ID does not exist");
                }
                catch (Exception ex)
                {
                    AuthException ex2 = new AuthException("Authentication failed", ex);
                    ex2.Data["UserId"] = userid;
                    throw ex2;
                }

                try
                {
                    string cstring = (new CasUsers()).MyDBServerObject(wsid.Value).ConnectionString;

                    bool tableExists = (new MyDBJobs()).MyDBTableExists(wsid.Value, table_id);
                    var task = Request.Content.ReadAsStreamAsync();
                    task.Wait();
                    Stream stream = task.Result;

                    using (CSVDataReader csvr = new CSVDataReader(new StreamReader(stream)))
                    {
                        csvr.UploadTo(cstring, table_id, tableExists);
                    }
                }
                catch (Exception ex)
                {
                    Exception ex2 = new Exception("Failed to upload table data", ex);
                    ex2.Data["UserId"] = userid;
                    throw ex2;
                }

                Message message = log.CreateInfoMessage("Data uploaded into table: " + table_id);
                message.UserId = userid;
                log.SendMessage(message);

                return ControllerContext.Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                throw new AuthException("User not authenticated");
            }
        }
    }
}
