using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Drawing;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Photo_Shared.Models;
using System.Collections;
using System.IO;

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

        // GET: Photos
        public ActionResult Index()
        {

            ViewBag.urlImage = getUrlImage();
            return View(db.Photos.ToList());
        }


        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;
        }


        private Hashtable getUrlImage()
        {
            Hashtable listUrl = new Hashtable();

            foreach(var v in db.Photos.ToList())
            {
                Image image = ByteArrayToImagebyMemoryStream(v.PhotoFile);
                string PhyPath = Server.MapPath("~") + @"\img\image" + v.PhotoID + ".jpg";
                string path = Request.Url.GetLeftPart(UriPartial.Authority) + @"\img\image"+v.PhotoID+".jpg";
                image.Save(PhyPath);
                listUrl[v.PhotoID] = path;
            }
            return listUrl;
            
        }

        private string getUrlImageByID(int i)
        {
            var v = db.Photos.Find(i);
                Image image = ByteArrayToImagebyMemoryStream(v.PhotoFile);
                string PhyPath = Server.MapPath("~") + @"\img\image" + v.PhotoID + ".jpg";
                string path = Request.Url.GetLeftPart(UriPartial.Authority) + @"\img\image" + v.PhotoID + ".jpg";
                image.Save(PhyPath);
                return path;
        }


        // GET: Photos/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Photo photo = db.Photos.Find(id);
            if (photo == null)
            {
                return HttpNotFound();
            }
            ViewBag.Comments = photo.Comments;
            ViewBag.URL = getUrlImageByID(photo.PhotoID);
            return View(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 = "PhotoID,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("~/img/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("Index");
            }

            return View(photo);
        }

        // GET: Photos/Edit/5
        public ActionResult Edit(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", "AccessDenied");
            }
            if (photo == null)
            {
                return HttpNotFound();
            }

            ViewBag.URL = getUrlImageByID(photo.PhotoID);
            return View(photo);
        }

        // POST: Photos/Edit/5
        // 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 Edit([Bind(Include = "PhotoID,Title,PhotoFile,Description,CreatedDate,Owner")] Photo photo)
        {
            if (ModelState.IsValid)
            {
                db.Entry(photo).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            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", "AccessDenied"); 
            }
            if (photo == null)
            {
                return HttpNotFound();
            }
            ViewBag.URL = getUrlImageByID(photo.PhotoID);
            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);
        }
    }
}
