using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using TP02Photo_sharing.Models;

namespace TP02Photo_sharing.Controllers
{
    [Authorize]
    public class PhotosController : Controller
    {
        private PhotoSaringDB db = new PhotoSaringDB();


        public static byte[] ImageToByteArray(string imagefilePath)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(imagefilePath);
            byte[] imageByte = ImageToByteArraybyMemoryStream(image);
            image.Dispose();
            return imageByte;
        }

        private static byte[] ImageToByteArraybyMemoryStream(Image image)
        {
            MemoryStream ms = new MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }
        public static Image ByteArrayToImagebyMemoryStream(byte[] imageByte)
        {
            MemoryStream ms = new MemoryStream(imageByte);
            Image image = Image.FromStream(ms);
            return image;
        }



        public ActionResult Suivant(int? id)
        {
            var l = db.Photos.ToList();
            int i = 0;
            while ((i < l.Count) && (l.ElementAt(i).ID != id))
            { i++; }
            Photo p;
            if (i == l.Count - 1) p = getPhotoByOrder(l.Count - 1);
            else p = getPhotoByOrder(i + 1);
            return View("Index", p);
        }

        public ActionResult Precedant(int? id)
        {
            var l = db.Photos.ToList();
            int i = 0;
            while ((i < l.Count) && (l.ElementAt(i).ID != id))
            { i++; }
            Photo p;
            if (i > 0) p = getPhotoByOrder(i - 1);
            else p = getPhotoByOrder(0);
            return View("Index", p);
        }
        // GET: /Photos/
        public ActionResult Index(int? id)
        {
            Photo v;
            if (id != null)
                v = getPhotoByID(id.Value);
            else v = getPhotoByOrder(0);
            return View(v);
        }

        private Photo getPhotoByOrder(int i)
        {
            if (db.Photos.ToList().Count > 0)
            {
                var v = db.Photos.ToList().ElementAt(i);
                Image image = ByteArrayToImagebyMemoryStream(v.PhotoFile);
                string PhyPath = Server.MapPath("~") + @"\images\image.jpg";
                string path = Request.Url.GetLeftPart(UriPartial.Authority) + @"\images\image.jpg";
                image.Save(PhyPath);
                ViewBag.IMAGE = path;
                return v;
            }
            else return new Photo();
        }
        private Photo getPhotoByID(int i)
        {
            if (db.Photos.ToList().Count > 0)
            {
                var v = db.Photos.Find(i);
                Image image = ByteArrayToImagebyMemoryStream(v.PhotoFile);
                string PhyPath = Server.MapPath("~") + @"\images\image.jpg";
                string path = Request.Url.GetLeftPart(UriPartial.Authority) + @"\images\image.jpg";
                image.Save(PhyPath);
                ViewBag.IMAGE = path;
                return v;
            }
            else return new Photo();
        }

        
        // GET: /Photos/Create
        public ActionResult Create()
        {
            
            return View();
        }

        // POST: /Photos/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Title,image,Description,CreatedDate")] Photo photo)
        {
            if (ModelState.IsValid)
            {
                photo.Owner = System.Web.HttpContext.Current.User.Identity.Name;
                photo.CreatedDate = DateTime.Now;
                string filePath = "";
                if (photo.image != null && photo.image.ContentLength > 0)
                {
                    filePath = Path.Combine(Server.MapPath("~/images/uploads"), Path.GetFileName(photo.image.FileName));
                    photo.image.SaveAs(filePath);
                }

                photo.PhotoFile = ImageToByteArray(filePath);
                db.Photos.Add(photo);
                db.SaveChanges();
                System.IO.File.Delete(filePath);
                return RedirectToAction("Suivant", db.Photos.ToList().ElementAt(db.Photos.ToList().Count - 1));
            }

            return View(photo);
        }

        

        // GET: /Photos/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Photo photo = db.Photos.Find(id);
            if (photo.Owner != System.Web.HttpContext.Current.User.Identity.Name)
            { return RedirectToAction("Index","NonAuth"); }
            if (photo == null)
            {
                return HttpNotFound();
            }
            var v = getPhotoByID(photo.ID);
            return View(photo);
        }

        // POST: /Photos/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Photo photo = db.Photos.Find(id);
            db.Photos.Remove(photo);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
