using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CARRE_DSS2.Models;
using Microsoft.AspNet.Identity;

namespace CARRE_DSS2.Controllers
{
    public class PatientsController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        // GET: Patients
        [Authorize]
        public ActionResult Index()
        {
            string userId = User.Identity.GetUserId();
            var patients = db.Users.Where(u => u.Id == userId).First().Patients;
            return View(patients);
        }

        // GET: Patients/Details/rugodzinski
        [Authorize]
        public ActionResult Details(string username)
        {
            if (username == null)
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            var userId = User.Identity.GetUserId();
            var patient = db.Users.Where(u => u.Id == userId).First().Patients.Where(p => p.UserName == username).First();

            if (patient == null)
                return HttpNotFound();

            return View(patient);
        }

        // GET: Patients/Create
        [Authorize]
        public ActionResult Create()
        {
            ViewBag.Message = "";
            return View();
        }

        // GET: Patients/Measurement/rugodzinski/Age
        [Authorize]
        public ActionResult Measurement(string username, string measurementName)
        {
            /// Only for temporary poprpouse

            var patient = db.Patients.Where(p => p.UserName == username).First();
            var node = db.MeasurementBindings.Where(mb => mb.Name == measurementName).First().MeasurementNode;
            var measurment = new Measurement(patient, node);

            return View(measurment);
        }

        // POST: Patients/Create
        [HttpPost]
        [Authorize]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Token")] Patient p)
        {
            ViewBag.Message = "";
            try
            {
                var privRepo = new CarreRestFull();
                var pNew = privRepo.validateToken(p.Token);

                if (pNew == null)
                {
                    ViewBag.Message = "ERROR";
                    return View(p);
                }

                if (db.Patients.Where(p2 => p2.Token == p.Token).Any())
                {
                    //checking if particular patient is already attached to medical expert
                    var userId = User.Identity.GetUserId();
                    var exist = db.Users.Where(u => u.Id == userId).First().Patients.Where(p2 => p2.Token == p.Token).Any();
                    if (exist)
                    {
                        ViewBag.Message = "EXIST";
                        return View(p);
                    }
                    else
                        db.Patients.Where(p2 => p2.Token == p.Token).First().AttachedExperts.Add(db.Users.Where(u => u.Id == userId).First());
                }
                else
                {
                    p.Email = pNew.Email;
                    p.UserName = pNew.UserName;
                    p.GraphName = pNew.GraphName;
                    var userId = User.Identity.GetUserId();
                    p.AttachedExperts.Add(db.Users.Where(u => u.Id == userId).First());
                    db.Patients.Add(p);
                }
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                ViewBag.Message = "ERROR";
                return View(p);
            }
        }



        // GET: Patients/Delete/5
        [Authorize]
        public ActionResult Delete(string username, bool? error)
        {
            if (username == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Patient patient = db.Patients.Where(p => p.UserName == username).First();

            if (patient == null)
            {
                return HttpNotFound();
            }

            var userId = User.Identity.GetUserId();
            if (!patient.AttachedExperts.Where(ex => ex.Id == userId).Any())
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if (error != null)
                ViewBag.Error = true;
            return View(patient);
        }

        // POST: Patients/Delete/5
        [HttpPost, ActionName("Delete")]
        [Authorize]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string username)
        {
            var userId = User.Identity.GetUserId();

            Patient patient = db.Patients.Where(p => p.UserName == username).First();

            var user = patient.AttachedExperts.Where(u => u.Id == userId).First();
            patient.AttachedExperts.Remove(user);

            if(!patient.AttachedExperts.Any())
            {
                db.Patients.Remove(patient);
            }

            try
            {
                db.SaveChanges();
            }
            catch
            {
                return RedirectToAction("Delete", new { username = username, error = true });
            }

            return RedirectToAction("Index");
        }
    }
}
