using System;
using System.Linq;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ErsPos.Service.ProductRepository;
using ErsPos.Service.UserRepository;
using ErsPos.Service.RestaurantRepository;
using ErsPos.Service.ViewModels;
using System.Net;
using BeachOrder.ActionFilters;

namespace BeachOrder.Controllers
{
    
    public class HomeController : Controller
    {
        //[LisansFilter]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JObject GetAll(string DepNo = "")
        {
            using (ProductRepository repo = new ProductRepository())
            {
                var p = repo.GetList(DepNo);
                return JObject.FromObject(new { p });
            }
        }

        [HttpGet]
        public JObject DeskList(string departmentId)
        {
            if (String.IsNullOrEmpty(departmentId))
            {
                return JObject.FromObject(new Result { Error = "DepartmanId null olamaz!" });
            }
            else
            {
                using (RestaurantRepository repo = new RestaurantRepository())
                {
                    try
                    {
                        var desks = repo.GetDeskList(departmentId).ToList();
                        var paymentTypes = repo.GetPaymentTypes();
                        return JObject.FromObject(new { desks });
                    }
                    catch (Exception ex)
                    {
                        return JObject.FromObject(new Result { Error = ex.Message });
                    }
                }
            }
        }

        // [HttpGet]
        public JObject GetPaymentTypes()
        {
            using (RestaurantRepository repo = new RestaurantRepository())
            {
                try
                {
                    var paymentTypes = repo.GetPaymentTypes();
                    return JObject.FromObject(new { paymentTypes });
                }
                catch (Exception ex)
                {
                    return JObject.FromObject(new { paymentTypes = "[]" });
                }
            }
        }

        [HttpGet]
        public JsonResult Login(string departmanCode, string password)
        {
            if (String.IsNullOrEmpty(departmanCode) || String.IsNullOrEmpty(password))
            {
                return Json(new Result { Error = "Kulanıcı bilgileri boş olamaz!" });
            }
            else
            {
                using (UserRepository repo = new UserRepository())
                {
                    try
                    {
                        var _user = repo.Login(departmanCode, password);
                        if (_user == null)
                        {
                            return Json(new Result { Error = "Kullanıcı Bulunamadı" });
                        }
                        else
                        {
                            var roles = repo.GetRoles(int.Parse(_user.RoleId));
                            return Json(new { user = _user, roles = roles });
                        }
                    }
                    catch (Exception ex)
                    {
                        return Json(new Result { Error = ex.Message });
                    }
                }
            }
        }
        [HttpGet]
        public JsonResult AddOrder(string data)
        {
            if (String.IsNullOrEmpty(data))
            {
                return Json(new Result { Error = "Herhangi bir sipariş isteği bulunamadı!" });
            }

            else
            {
                if (!CheckNet())
                {
                    return Json(new { Error = "NetWork Error", Data = data });
                }
                else
                {
                    var request = JsonConvert.DeserializeObject<System.Collections.Generic.List<RequestViewModel>>(data);
                    //JsonConvert.DeserializeObject<List<RequestViewModel>>(data);
                    using (ProductRepository repo = new ProductRepository())
                    {
                        try
                        {
                            string message = "";
                            foreach (var item in request)
                            {
                                repo.Add(item);
                                message += item.DeskNo + ",";
                            }

                            return Json(new Result { Message = message + " numaralı masa için sipariş gönderildi." });
                        }
                        catch (Exception ex)
                        {
                            return Json(new Result { Error = ex.Message });
                        }

                    }
                }
            }
        }

        [HttpGet]
        public JObject ViewOrClose(string data /*string isViewOrClose,string departmentId="", string deskNo ="",string paymentType=""*/)
        {
            if (!String.IsNullOrEmpty(data))
            {
                var model = JsonConvert.DeserializeObject<SeeOrCloseModel>(data);
                if (String.IsNullOrEmpty(model.DepartmentId) || String.IsNullOrEmpty(model.DeskNo))
                {
                    return JObject.FromObject(new Result { Error = "DeparmanId ve Masa numarası boş olamaz!" });
                }
                else
                {
                    using (ProductRepository repo = new ProductRepository())
                    {
                        try
                        {
                            if (model.IsViewOrClose == "view")
                            {
                                var view = repo.View(model.DepartmentId, model.DeskNo);
                                return JObject.FromObject(new { view });
                            }
                            else if (model.IsViewOrClose == "close")
                            {
                                var message = repo.Close(model);
                                return JObject.FromObject(new Result { Message = message });
                            }
                            else
                            {
                                return JObject.FromObject(new Result { Message = "Tanımsız istek!" });
                            }
                        }
                        catch (Exception ex)
                        {
                            return JObject.FromObject(new Result { Error = ex.Message });
                        }
                    }
                }
            }
            else
            {
                return JObject.FromObject(new Result { Message = "Json data boş olamaz" });
            }
        }

        public JObject AddOrderWithQrCode(string data = "")
        {
            if (string.IsNullOrEmpty(data))
            {
                return JObject.FromObject(new Result { Error = "Error" });
            }
            else
            {
                var model = JsonConvert.DeserializeObject<RequestViewModel>(data);
                if (model != null)
                {
                    // ekle
                    return JObject.FromObject(new Result { Message = "OK" });

                    // kapat
                }
                else
                {
                    return JObject.FromObject(new Result { Error = "Error" });
                }
            }
        }

        public Boolean CheckNet()
        {
            try
            {
                using (var client = new WebClient())
                {
                    using (client.OpenRead("http://clients3.google.com/generate_204"))
                    {
                        return true;
                    }
                }
            }
            catch
            {
                return false;
            }
        }

        public JObject UploadImage()
        {
            try
            {
                System.Collections.Generic.List<FileViewModel> files = new System.Collections.Generic.List<FileViewModel>();
                if (Request.Files != null)
                {
                    foreach (string upload in Request.Files)
                    {
                        System.Web.HttpPostedFileBase file = Request.Files[upload];
                        string fileName = Guid.NewGuid().ToString() + "-" + file.FileName.Replace(" ", "").Replace(",", "-").Replace("/", "-");
                        file.SaveAs(Server.MapPath("~/Upload/" + fileName));
                        files.Add(new FileViewModel { Name = fileName, Path = "/Upload/" + fileName });
                    }

                    return JObject.FromObject(new { files = files });

                }
                else
                {
                    return JObject.FromObject(new Result { Error = "Hata Oldu." });
                }

            }
            catch (Exception ex)
            {
                return JObject.FromObject(new Result { Error = "Hata Oldu." });
            }
        }

        public JObject AddDetail(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return JObject.FromObject(new Result { Error = "data boş olamaz" });
            }
            else
            {
                try
                {
                    var model = JsonConvert.DeserializeObject<ProductDetailViewModel>(data);
                    using (ProductRepository repo = new ProductRepository())
                    {
                        var result = repo.AddDetail(model);
                        if (result.Error != "")
                        {
                            JObject.FromObject(new Result { Error = "NOK" });
                        }
                        else
                        {
                            return JObject.FromObject(new Result { Message = "OK" });
                        }
                    }
                    return JObject.FromObject(new Result { Message = "OK" });
                }
                catch (Exception ex)
                {
                    return JObject.FromObject(new Result { Error = "NOK" });
                }
            }
        }
    }
}