Monday, 31 March 2014

controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Gammers.Models;
using Gammers.Repository;
using Gammers.Helpers;
using System.Web.Optimization;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Drawing;
using System.ComponentModel;
using System.Web.Hosting;
using System.Drawing.Imaging;
using System.Net.Http.Headers;
using System.Diagnostics;
using HoiioSDK.NET;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Globalization;
using System.Data;

namespace Controllers
{
    public class UserController : ApiController
    {

        [HttpPost]
        [ActionName("AuthenticateUser")]
        public dynamic AuthenticateUser(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            var Result = Convert.ToInt32(new UserRepository().AuthentucateUser(user.EmailId, user.ContactNo));
            if (Result == -1)
                dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Error, StatusConstants.Error, null, "Email does not exists."); // msg as per client said
            else if (Result == -2)
                dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Error, StatusConstants.Error, null, "Contact does not exists."); //msg as per client said
            else
            {
                Random rnd = new Random();
                string code = rnd.Next(1000, 10000).ToString();
                if (code.Length == 3)
                    code = code + "0";
                else if (code.Length == 2)
                    code = code + "00";
                dicto = new Dictionary<string, dynamic>();


                //-------------------Send Email with varfication code--------------
                bool EmailStatus = EmailHelper.SendEmailForVarificationCode(user.EmailId, code, user.ContactNo);
                if (EmailStatus == true)
                {
                    dicto.Add("code", code);
                    dicto.Add("Result", "Email Send Successfully");
                }
                else
                    dicto.Add("Result", "Email Sending fail");
                //-------------------End-------------------------------------------
            }
            return dicto;
        }

        private int GetTempId(string emailid)
        {
            if (emailid == Convert.ToString("abc@gmail.com").ToLower())
                return 1;
            else if (emailid == Convert.ToString("xyz@gmail.com").ToLower())
                return 2;
            else if (emailid == Convert.ToString("Gee@gmail.com").ToLower())
                return 3;
            else if (emailid == Convert.ToString("dip@gmail.com").ToLower())
                return 4;
            else if (emailid == Convert.ToString("mj@gmail.com").ToLower())
                return 5;
            else if (emailid == Convert.ToString("roj@gmail.com").ToLower())
                return 6;
            else
                return 0;
        }

        [HttpPost]
        [ActionName("RegisterUser")]
        public dynamic RegisterUser(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            user.DeviceId = user.DeviceId.Replace(" ","");
            Pro_UserDetail Userdetail = new UserRepository().InsertUser(user);
            if (Userdetail.UserId > 0)
            {
                dicto.Add("Message", Userdetail.Message);
                dicto.Add("UserId", Userdetail.UserId);
                dicto.Add("CreatedOn", Userdetail.CreatedOn);
            }
            else
            {
                dicto.Add("Message", Userdetail.Message);
                dicto.Add("UserId", Userdetail.UserId);
                dicto.Add("CreatedOn", Userdetail.CreatedOn);
            }
         
            return dicto;
        }

        [HttpPost]
        [ActionName("RefreshContacts")]
        public dynamic RefreshContacts(Pro_ContactDetails user)
        {
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            i = Convert.ToInt32(new ContactDetailsRepository().UpdateIsFriend(user.UserId, user.CreatedOn));

            if (i == 1)
            {
                var ContactDetails = new ContactDetailsRepository().GetFriendList(user.UserId, user.CreatedOn);
                if (ContactDetails.Count > 0)
                    dicto.Add("Result", ContactDetails);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertContactDetails")]
        public dynamic InsertContactDetails(Pro_ContactDetails user)
        {
            string contacts = string.Empty;
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            contacts = Convert.ToString(user.ContactArray);
            JavaScriptSerializer jss = new JavaScriptSerializer();
            List<Pro_ContactDetails_Api> Contactlist = jss.Deserialize<List<Pro_ContactDetails_Api>>(contacts);
            string result = new ContactDetailsRepository().InsertContacts(Contactlist, user.UserId, user.CreatedOn);
            if (result == "Success")
            {
                i = Convert.ToInt32(new ContactDetailsRepository().UpdateIsFriend(user.UserId, user.CreatedOn));
            }
            if (i == 1)
            {
                var ContactDetails = new ContactDetailsRepository().GetFriendList(user.UserId, user.CreatedOn);
                if (ContactDetails != null)
                    dicto.Add("Result", ContactDetails);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("RestoreFriendList")]
        public dynamic RestoreFriendList(Pro_FriendsContactDetails_Api user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetails = new ContactDetailsRepository().RestoreFriendList(Convert.ToInt32(user.UserId));
            if (UserDetails.Count > 0)
                dicto.Add("Result", UserDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetFeaturedMember")]
        public dynamic GetFeaturedMember(Pro_UserMaster_Api user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetails = new UserRepository().GetFeaturedMember(user.UserId);
            if (UserDetails.UserId > 0)
                dicto.Add("Result", UserDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedPicture")]
        public dynamic GetHighlightedPicture(Pro_PictureShareMaster_Api Picture)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var PictureDetails = new PictureShareRepository().GetTotalSharePicture(Picture.UserId);
            if (PictureDetails.Count > 0)
                dicto.Add("Result", PictureDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedVideos")]
        public dynamic GetHighlightedVideos(Pro_VideoShareMaster_Api Video)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var VideoDetails = new VideoShareRepository().GetTotalShareVideos(Video.UserId);
            if (VideoDetails.Count > 0)
                dicto.Add("Result", VideoDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetUserContactDetails")]
        public dynamic GetUserContactDetails(Pro_UserContact user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserContactDetails = new UserContactRepository().GetUserContactDetails(user.UserId, user.Flag);
            if (UserContactDetails.Count > 0)
                dicto.Add("Result", UserContactDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetUserProfile")]
        public dynamic GetUserProfile(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserProfile = new UserRepository().GetUserProfile(user.UserId);

            if (UserProfile.UserId > 0)
                dicto.Add("Result",UserProfile);
            else
                dicto.Add("Status",Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("UpdateProfileAndProfilePic")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> UpdateProfileAndProfilePic()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var user = new Pro_UserMaster();
            bool Status = false;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/ProfilePicture");
            var provider = new MultipartFormDataStreamProvider(root);

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "UserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.UserId = Convert.ToInt32(val);
                                }
                                if (string.Equals(key, "UserName", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.UserName = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Sex", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Sex = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Birthdate", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Birthdate = Convert.ToDateTime(val);
                                }
                                else if (string.Equals(key, "AboutYou", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.AboutYou = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Intrestes", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Intrestes = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Hobbies", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Hobbies = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Favoritemovies", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Favoritemovies = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "LookingFor", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.LookingFor = Convert.ToString(val);
                                }
                                break;
                            }
                    }

                    if (user.UserId > 0)
                    {
                        if (provider.FileData.Count != 0)
                        {
                            string OldPic = new UserRepository().GetProfilePic(user.UserId);
                            if (!string.IsNullOrEmpty(OldPic))
                            {
                                if (File.Exists(root + "/" + OldPic))
                                {
                                    File.Delete(root + "/" + OldPic);
                                    File.Delete(root + "/" + "Thumb_" + OldPic);
                                }
                            }
                            //var ProfilePic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + user.UserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                            //var ProfilePic = "ProfilePic_" + user.UserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                            var ProfilePic = "ProfilePic_" + user.UserId + ".png";
                            var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                            var img = System.Drawing.Image.FromFile(finfo.FullName);
                            //img = Helpers.ImageExtensions.Resize(img, Width, Height);
                            var converter = new System.Drawing.ImageConverter();
                            var b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                            user.ProfilePic = ProfilePic;
                            user.Mode = "UpdateProfilePic";
                            int retval = Convert.ToInt32(new UserRepository().SaveProfile(user));
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, ProfilePic), img.Width, img.Height);
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + ProfilePic), 100, 100);
                            img.Dispose();
                            Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                            //System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, userImage));
                            if (retval == 0)
                            {
                                if (File.Exists(root + "/" + ProfilePic))
                                {
                                    File.Delete(root + "/" + ProfilePic);
                                    File.Delete(root + "/" + "Thumb_" + ProfilePic);
                                }
                                Status =Convert.ToBoolean(0);
                            }
                        }

                        user.Mode = "UpdateProfile";
                        int Returnval = Convert.ToInt32(new UserRepository().SaveProfile(user));
                        if (Returnval > 0)
                            Status = Convert.ToBoolean(1);
                        else
                            Status = Convert.ToBoolean(0);

                    }
                    Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
                    dicto.Add("Status", Status);
                    return dicto;
                   // return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, Status);
                }
            );
            return task;
        }

        public dynamic GetVideo(int id)
        {
            Pro_VideoMaster objpicture = new Pro_VideoMaster();
            objpicture = new VideoRepository().GetVideoById(id);
            byte[] Content = objpicture.VideoContent;
            //MemoryStream ms = new MemoryStream(Content);

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(Content);
            object rval = formatter.Deserialize(stream);
            stream.Close();
            return rval;
        }

        //public HttpResponseMessage Get(int id)
        //{
        //    Pro_PictureMaster objpicture = new Pro_PictureMaster();
        //    objpicture = new PictureRepository().GetPictureById(id);
        //    byte[] imgData = objpicture.ImageContent;
        //    MemoryStream ms = new MemoryStream(imgData);
        //    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        //    response.Content = new StreamContent(ms);
        //    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");

        //    return response;
        //}
        [HttpPost]
        [ActionName("InsertChat")]
        public dynamic InsertChat(Pro_ChatHistoryMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto;
            if (chatHistory.GroupId != 0)
            {
                Pro_GroupChatDateDetail chat = new ChatHistoryRepository().InsertGroupChat(chatHistory);
                dicto = new Dictionary<string, dynamic>();
                if (chat.Status == true)
                {
                    //dicto.Add("ChatId", ChatId);
                    dicto.Add("Result", chat);
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                Pro_ChatDateDetail Chat = new ChatHistoryRepository().SaveChat(chatHistory);
                dicto = new Dictionary<string, dynamic>();
                if (Chat.ServerID > 0)
                {
                    dicto.Add("Result", Chat);
                    //dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                {
                    dicto.Add("Status", Convert.ToBoolean(0));
                }
            }

            return dicto;

        }

        [HttpPost]
        [ActionName("InsertChatwithImageOrVideo")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> InsertChatwithImageOrVideo()
        {
            HttpRequestMessage request = Request;
            Pro_GroupChatDateDetail chatdetail = new Pro_GroupChatDateDetail();
            Pro_ChatDateDetail Chat = new Pro_ChatDateDetail();
            int Height = 0;
            int Width = 0;
            string Upload = string.Empty;
            string FileName = string.Empty;
            byte[] buffer = null;
            long offset = 0;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var chathistory = new Pro_ChatHistoryMaster();
            string strmsg = string.Empty;
            //var root =Helpers.ConstantValues.RootUrl;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/ChatHistory");
            var provider = new MultipartFormDataStreamProvider(root);
            Dictionary<string, dynamic> dicto = null;
            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "FromId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.FromId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ToId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.ToId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "GroupId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.GroupId = Convert.ToInt32(val);
                                }
                                //else if (string.Equals(key, "ChatOn", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        chathistory.ChatOn = Convert.ToDateTime(val);
                                //}
                                else if (string.Equals(key, "Upload", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        Upload = val;
                                }
                                //else if (string.Equals(key, "FileName", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        FileName = val;
                                //}
                                //else if (string.Equals(key, "buffer", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        buffer = Encoding.ASCII.GetBytes(val);
                                //}
                                //else if (string.Equals(key, "Offset", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        offset =  Convert.ToInt64(val);
                                //}
                                break;
                            }
                    }

                    if (Upload == "Image")
                    {
                        var chatId = 0;
                        string msg = string.Empty;

                        //var userImage = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                        var userImage = Helpers.HelperFunctions.CreateUniqueFileName() + ".png";
                        chathistory.ImagePath = userImage;

                        var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                        var img = System.Drawing.Image.FromFile(finfo.FullName);
                        //img = Helpers.ImageExtensions.Resize(img, Width, Height);

                        var converter = new System.Drawing.ImageConverter();
                        var b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                        bool retval = Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, userImage), img.Width, img.Height);

                        img.Dispose();
                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                        dicto = new Dictionary<string, dynamic>();
                        if (retval)
                        {
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + userImage), 100, 100);
                            if (chathistory.GroupId != 0)
                            {
                                chatdetail = new ChatHistoryRepository().InsertGroupChat(chathistory);
                                if (chatdetail.Status == true)
                                {
                                    dicto.Add("Result", chatdetail);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + userImage))
                                        DeleteImageVideo(root + "/" + userImage);
                                    dicto.Add("Message", msg);
                                }
                            }
                            else
                            {
                                Chat = new ChatHistoryRepository().SaveChat(chathistory);
                                //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                                if (Chat.ServerID > 0)
                                {
                                    dicto.Add("Result", Chat);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + userImage))
                                    {
                                        DeleteImageVideo(root + "/" + userImage);
                                        DeleteImageVideo(root + "/" + userImage + "_Thumb");
                                    }
                                    dicto.Add("Message", "File Upload fail");
                                }
                            }
                        }
                        else
                        {
                            dicto.Add("Message", "File Uploaded Fail.");
                        }
                    }
                    else
                    {
                        dicto = new Dictionary<string, dynamic>();
                        string msg = string.Empty;
                        var UserVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                        chathistory.VideoPath = UserVideo;

                        var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, UserVideo));
                        if (File.Exists(root + "/" + UserVideo))
                        {
                            if (chathistory.GroupId != 0)
                            {
                                chatdetail = new ChatHistoryRepository().InsertGroupChat(chathistory);
                                if (chatdetail.Status == true)
                                {
                                    dicto.Add("Result", chatdetail);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + UserVideo))
                                        DeleteImageVideo(root + "/" + UserVideo);
                                    dicto.Add("Message", msg);
                                }
                            }
                            else
                            {
                                Chat = new ChatHistoryRepository().SaveChat(chathistory);
                                //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                                if (Chat.ServerID > 0)
                                {
                                    dicto.Add("Result", Chat);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + UserVideo))
                                        DeleteImageVideo(root + "/" + UserVideo);
                                    dicto.Add("Message", "File Upload fail");
                                }
                            }
                        }

                    }

                    return dicto;
                    //return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        public void DeleteImageVideo(string FilePath)
        {
            File.Delete(FilePath);
        }

        [HttpPost]
        [ActionName("GetMyNewMsg")]
        public dynamic GetMyNewMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_ChatHistoryDetail> chats = new ChatHistoryRepository().GetMyNewMsg(Chat.FromId, Chat.ToId, Chat.ChatDate);
            Pro_Status Status = new UserRepository().GetUserStatus(Chat.FromId,Chat.ChatId);

            if (chats.Count > 0)
            {
                dicto.Add("Result", chats);
                dicto.Add("IsOnline", Status.IsOnline);
                dicto.Add("IsTyping", Status.IsTyping);
            }
            else
            {
                dicto.Add("IsOnline", Status.IsOnline);
                dicto.Add("IsTyping", Status.IsTyping);
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("GetGroupChatHistory")]
        public dynamic GetGroupChatHistory(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_GroupChatHistoryDetail> chats = new ChatHistoryRepository().GetGroupChatHistory(Chat.ToId, Chat.GroupId);
            if (chats.Count > 0)
                dicto.Add("Result", chats);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetMyNewGroupMsg")]
        public dynamic GetMyNewGroupMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_GroupChatHistoryDetail> chats = new ChatHistoryRepository().GetMyNewGroupMsg(Chat.ToId, Chat.GroupId, Chat.ChatDate);
            if (chats.Count > 0)
                dicto.Add("Result", chats);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertGroup")]
        public dynamic InsertGroup(Pro_GroupMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            if (chatHistory.ListofUsers != null)
            {
                chatHistory.CreatedOn = DateTime.UtcNow;
                int GroupId = Convert.ToInt32(new GroupRepository().SaveGroup(chatHistory));
                if (GroupId > 0)
                    dicto.Add("GroupId", GroupId);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetAllGroupsByUserId")]
        public dynamic GetAllGroupsByUserId(int UserId)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserGroups = new GroupRepository().GetAllGroupsByUserId(UserId);
            if (UserGroups != null)
               dicto.Add("Result", UserGroups);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetGroupsByGroupId")]
        public dynamic GetGroupsByGroupId(int GroupId)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var groupsDetail = new GroupRepository().GetGroupsByGroupId(GroupId);

            if (groupsDetail != null)
                dicto.Add("Result", groupsDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("GetAllGroupUser")]
        public dynamic GetAllGroupUser(Pro_GroupMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var groupsDetail = new GroupRepository().GetAllGroupUser(chatHistory.GroupId);

            if (groupsDetail != null)
               dicto.Add("Result", groupsDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        #region Webposter current

        [HttpPost]
        [ActionName("AddToWebPoster1")]
        public dynamic AddToWebPoster1(Pro_WebPoster objWebPoster)
        {
            string strmsg = string.Empty;
            bool IsDataRemain;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            if (objWebPoster.Share == 0)
            {
                long offset = Convert.ToInt64(objWebPoster.Offset);
                string path = string.Empty;
                if (objWebPoster.FromCommunity == true)
                    path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["CommunityUrl"]);
                else
                    path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WebPosterUrl"]);

                if (objWebPoster.ContentType == "Image")
                    objWebPoster.ChatImgName = objWebPoster.FileName;
                else
                    objWebPoster.ChatVideoName = objWebPoster.FileName;
                if (objWebPoster.IsUploadingEnd == true)
                {
                    new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    IsDataRemain = false;
                }
                else
                {
                    IsDataRemain = new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    dicto.Add("Success", IsDataRemain);
                }
                if (IsDataRemain == false)
                {
                    if (objWebPoster.ContentType == "Image")
                    {
                        //--------------Thumb image------------------------------------
                        if (objWebPoster.ContentType == "Image")
                            Helpers.HelperFunctions.SaveThumbImage(path + objWebPoster.FileName, 100, 100, "Thumb_");
                        //--------------End Thumb image--------------------------------


                        int pictureId = Convert.ToInt32(new PictureRepository().SaveUserPicture(objWebPoster.LoginUserId, objWebPoster.ChatImgName, Convert.ToDateTime(objWebPoster.CreatedOn), objWebPoster.FromCommunity));
                        if (pictureId > 0)
                        {
                            if (objWebPoster.FromCommunity == true)
                            {
                                dicto.Add("Status", Convert.ToBoolean(1));
                                dicto.Add("ContentId", pictureId);
                            }
                            else
                                dicto.Add("Status", Convert.ToBoolean(1));
                        }
                        else
                        {
                            if (File.Exists(path + "/" + objWebPoster.FileName))
                            {
                                DeleteImageVideo(path + "/" + objWebPoster.FileName);
                                DeleteImageVideo(path + "/" + "Thumb_" + objWebPoster.FileName);
                            }
                            dicto.Add("Status", Convert.ToBoolean(0));
                        }

                    }
                    else
                    {

                        int VideoId = Convert.ToInt32(new VideoRepository().SaveUserVideo(objWebPoster.LoginUserId, objWebPoster.ChatVideoName, Convert.ToDateTime(objWebPoster.CreatedOn), objWebPoster.FromCommunity));
                        if (VideoId > 0)
                        {
                            if (objWebPoster.FromCommunity == true)
                            {
                                dicto.Add("Status", Convert.ToBoolean(1));
                                dicto.Add("ContentId", VideoId);
                            }
                            else
                                dicto.Add("Status", Convert.ToBoolean(1));
                        }
                        else
                        {
                            if (File.Exists(path + "/" + objWebPoster.FileName))
                            {
                                DeleteImageVideo(path + "/" + objWebPoster.FileName);
                            }
                            dicto.Add("Status", Convert.ToBoolean(0));
                        }
                    }
                }
            }
            else //---If Share
            {
                if (objWebPoster.ContentType == "Image")
                {
                    Pro_PictureShareMaster objPictureShare = new Pro_PictureShareMaster();
                    objPictureShare.UserId = objWebPoster.LoginUserId;
                    objPictureShare.PictureId = objWebPoster.ContentId;
                    objPictureShare.ShareId = objWebPoster.FromUserId;
                    objPictureShare.CreatedOn = objWebPoster.CreatedOn;
                    objPictureShare.FromCommunity = objWebPoster.FromCommunity;
                    int pictureShareId = Convert.ToInt32(new PictureShareRepository().SaveSharePicture(objPictureShare));
                    if (pictureShareId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
                else
                {
                    Pro_VideoShareMaster objVideoShare = new Pro_VideoShareMaster();
                    objVideoShare.UserId = objWebPoster.LoginUserId;
                    objVideoShare.VideoId = objWebPoster.ContentId;
                    objVideoShare.CreatedOn = DateTime.UtcNow.ToString();
                    objVideoShare.ShareId = objWebPoster.FromUserId;
                    objVideoShare.FromCommunity = objWebPoster.FromCommunity;
                    int VideoShareId = Convert.ToInt32(new VideoShareRepository().SaveShareVideo(objVideoShare));
                    if (VideoShareId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AddToWebPoster")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> AddToWebPoster()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var webposter = new Pro_WebPoster();
            string strmsg = string.Empty;
            string ContentType = string.Empty;
            string strChatContent = string.Empty;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/WebPoster");
            var provider = new MultipartFormDataStreamProvider(root);

            Image img = null;
            byte[] b = null;
            System.IO.FileInfo finfo = null;
            var webposterPic = "";
            var webposterVideo = "";

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "Share", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.Share = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "LoginUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.LoginUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "FromUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ContentType", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        ContentType = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "ContentId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.ContentId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "CreatedOn", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.CreatedOn = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "FromCommuniy", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromCommunity = Convert.ToBoolean(val);
                                }
                                break;
                            }
                    }

                    if (webposter.LoginUserId > 0)
                    {
                        if (webposter.Share == 0)
                        {
                            if (provider.FileData.Count != 0)
                            {
                                if (ContentType == "Image")
                                {
                                    //webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + ".png";
                                    finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                    img = System.Drawing.Image.FromFile(finfo.FullName);
                                    var converter = new System.Drawing.ImageConverter();
                                    b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                                    webposter.WebposterImg = webposterPic;
                                    DateTime dt = DateTime.UtcNow;
                                    //DateTime dt = Convert.ToDateTime(webposter.CreatedOn);
                                    int pictureId = Convert.ToInt32(new PictureRepository().SaveUserPicture(webposter.LoginUserId, webposterPic, dt, webposter.FromCommunity));

                                    if (pictureId > 0)
                                    {
                                        //----Image upload-----
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, webposterPic), img.Width, img.Height);
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + webposterPic), 100, 100);
                                        img.Dispose();
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End Image upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                                else if (ContentType == "Video")
                                {
                                    webposterVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposter.WebposterVideo = webposterVideo;
                                    DateTime dt = DateTime.UtcNow;
                                    int VideoId = Convert.ToInt32(new VideoRepository().SaveUserVideo(webposter.LoginUserId, webposterVideo, dt, webposter.FromCommunity));
                                    if (VideoId > 0)
                                    {
                                        //----video upload-----
                                        finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, webposterVideo));
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End video upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                            }
                        }
                        else
                        {
                            if (ContentType == "Image")
                            {
                                Pro_PictureShareMaster objPictureShare = new Pro_PictureShareMaster();
                                objPictureShare.UserId = webposter.LoginUserId;
                                objPictureShare.PictureId = webposter.ContentId;
                                objPictureShare.CreatedOn = DateTime.UtcNow.ToString();
                                objPictureShare.ShareId = webposter.FromUserId;
                                int pictureShareId = Convert.ToInt32(new PictureShareRepository().SaveSharePicture(objPictureShare));
                                if (pictureShareId > 0)
                                    strmsg = "1";
                                else
                                    strmsg = "0";
                            }
                            else if (ContentType == "Video")
                            {
                                Pro_VideoShareMaster objVideoShare = new Pro_VideoShareMaster();
                                objVideoShare.UserId = webposter.LoginUserId;
                                objVideoShare.VideoId = webposter.ContentId;
                                objVideoShare.CreatedOn = DateTime.UtcNow.ToString();
                                objVideoShare.ShareId = webposter.FromUserId;
                                int VideoShareId = Convert.ToInt32(new VideoShareRepository().SaveShareVideo(objVideoShare));
                                if (VideoShareId > 0)
                                    strmsg = "1";
                                else
                                    strmsg = "0";
                            }
                        }
                    }
                    return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        [HttpPost]
        [ActionName("AddChatToWebPoster1")]
        public dynamic AddChatToWebPoster1(Pro_WebPoster objWebPoster)
        {
            string msg = string.Empty;
            bool IsSuccess;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();


            if (objWebPoster.Share == 0)
            {
                long offset = Convert.ToInt64(objWebPoster.Offset);
                string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WebPosterUrl"]);
                if (objWebPoster.ContentType == "Image")
                    objWebPoster.ChatImgName = objWebPoster.FileName;
                else
                    objWebPoster.ChatVideoName = objWebPoster.FileName;
                if (objWebPoster.IsUploadingEnd == true)
                {
                    new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    IsSuccess = false;
                }
                else
                {
                    IsSuccess = new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    dicto.Add("Success", IsSuccess);
                }

                if (IsSuccess == false)
                {
                    Pro_webPosterChat objchat = new Pro_webPosterChat();
                    objchat.FromId = objWebPoster.LoginUserId;
                    objchat.ToId = objWebPoster.FromUserId;
                    objchat.GroupId = 0;
                    objchat.ChatOn = objWebPoster.CreatedOn;
                    if (objWebPoster.ContentType == "Image")
                    {
                        objchat.ContentType = "ChatImage";
                        objchat.Content = objWebPoster.ChatImgName;
                        //--------------Thumb image------------------------------------
                        if (objWebPoster.ContentType == "Image")
                            Helpers.HelperFunctions.SaveThumbImage(path + objWebPoster.FileName, 100, 100, "Thumb_");
                        //--------------End Thumb image--------------------------------
                    }
                    else if (objWebPoster.ContentType == "Video")
                    {
                        objchat.ContentType = "ChatVideo";
                        objchat.Content = objWebPoster.ChatVideoName;
                    }
                    else
                    {
                        objchat.ContentType = "ChatText";
                        objchat.Content = objWebPoster.TextMsg;
                    }

                    int webPosterId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                    if (webPosterId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        if (File.Exists(path + "/" + objWebPoster.FileName))
                        {
                            DeleteImageVideo(path + "/" + objWebPoster.FileName);
                            if (objchat.ContentType == "ChatImage")
                                DeleteImageVideo(path + "/" + "Thumb_" + objWebPoster.FileName);
                        }
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }

                }
            }
            else
            {
                Pro_WebPosterChatShare chatshare = new Pro_WebPosterChatShare();
                chatshare.UserId = objWebPoster.LoginUserId;
                chatshare.WPChatId = objWebPoster.ContentId;
                chatshare.ShareId = objWebPoster.FromUserId;
                chatshare.CreatedOn = objWebPoster.CreatedOn;
                int ChatId = Convert.ToInt32(new WebPosterChatShareRepository().SaveShareChat(chatshare));
                if (ChatId > 0)
                {
                    dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AddChatToWebPoster")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> AddChatToWebPoster()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var webposter = new Pro_WebPoster();
            string strmsg = string.Empty;
            string ContentType = string.Empty;
            string strChatContent = string.Empty;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/WebPoster");
            var provider = new MultipartFormDataStreamProvider(root);

            Image img = null;
            byte[] b = null;
            System.IO.FileInfo finfo = null;
            var webposterPic = "";
            var webposterVideo = "";

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "Share", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.Share = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "LoginUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.LoginUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "FromUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ContentType", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        ContentType = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "ContentId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.ContentId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "TextMsg", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        strChatContent = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "CreatedOn", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.CreatedOn = Convert.ToString(val);
                                }
                                break;
                            }
                    }

                    if (webposter.LoginUserId > 0)
                    {
                        if (webposter.Share == 0)
                        {
                            Pro_webPosterChat objchat = new Pro_webPosterChat();
                            objchat.FromId = webposter.LoginUserId;
                            objchat.ToId = webposter.FromUserId;
                            objchat.GroupId = 0;
                            objchat.ChatOn = DateTime.UtcNow.ToString();
                            if (provider.FileData.Count != 0)
                            {
                                if (ContentType == "Image")
                                {
                                    //webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + ".png";
                                    finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                    img = System.Drawing.Image.FromFile(finfo.FullName);
                                    var converter = new System.Drawing.ImageConverter();
                                    b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                                    //DateTime dt = Convert.ToDateTime(webposter.CreatedOn);
                                    objchat.ContentType = "ChatImage";
                                    objchat.Content = webposterPic;
                                    int pictureId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));

                                    if (pictureId > 0)
                                    {
                                        //----Image upload-----
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, webposterPic), img.Width, img.Height);
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + webposterPic), 100, 100);
                                        img.Dispose();
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End Image upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                                else if (ContentType == "Video")
                                {
                                    webposterVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    DateTime dt = DateTime.UtcNow;
                                    objchat.ContentType = "ChatVideo";
                                    objchat.Content = webposterVideo;
                                    int VideoId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                                    if (VideoId > 0)
                                    {
                                        //----video upload-----
                                        finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, webposterVideo));
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End video upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                            }
                            if (ContentType == "TextMsg")
                            {
                                objchat.ContentType = "ChatText";
                                objchat.Content = strChatContent;
                                int ChatId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                                if (ChatId > 0)
                                {
                                    strmsg = "1";
                                }
                                else
                                    strmsg = "0";
                            }
                        }
                        else
                        {
                            Pro_WebPosterChatShare chatshare = new Pro_WebPosterChatShare();
                            chatshare.UserId = webposter.LoginUserId;
                            chatshare.WPChatId = webposter.ContentId;
                            chatshare.ShareId = webposter.FromUserId;
                            chatshare.CreatedOn = DateTime.UtcNow.ToString();
                            int ChatId = Convert.ToInt32(new WebPosterChatShareRepository().SaveShareChat(chatshare));
                            if (ChatId > 0)
                            {
                                strmsg = "1";
                            }
                            else
                                strmsg = "0";
                        }
                    }
                    return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        [HttpPost]
        [ActionName("GetDatesForWebposter")]
        public dynamic GetDatesForWebposter(Pro_WebPoster objPro_WebPoster)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new WebPosterRepository().GetDatesForWebPoster(objPro_WebPoster);

            if (DateList.Count > 0)
            {
                if(DateList[0] == "2")
                    dicto.Add("Status", Convert.ToInt32(DateList[0]));
                else
                    dicto.Add("Result", DateList);
            }
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetDetailsForWebPoster")]
        public dynamic GetDetailsForWebPoster(Pro_WebPoster objProWebPoster)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new WebPosterRepository().GetDetailsForWebPosterByDate(objProWebPoster);

            if (DateList.Count > 0)
                dicto.Add("Result",DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("WelcomeHome")]
        public dynamic WelcomeHome(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CountDetail = new UserRepository().InsertLatLongAndUserStatus(user);

            if (user.UserId > 0)
                dicto.Add("Result",CountDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }


        [HttpPost]
        [ActionName("UserStatus")]
        public dynamic UserStatus(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CountDetail = new UserRepository().UserStatus(user);

            if (CountDetail > 0)
                 dicto.Add("Result",CountDetail);
            else
                 dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("UserPrivacySetting")] //for on and of
        public dynamic UserPrivacySetting(Pro_UserPrivacySetting user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetail = new UserRepository().UpdatePrivacySetting(user);

            if (UserDetail > 0)
                dicto.Add("Status", Convert.ToBoolean(1));
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }
        #endregion


        #region News

        [HttpPost]
        [ActionName("GetNewsCount")]
        public dynamic GetNewsCount(Pro_News objNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var newsCount = new NewsRepository().GetNewsCount(objNews);

            if (newsCount > 0)
                dicto.Add("Result",newsCount);
            else
                 dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }


        [HttpPost]
        [ActionName("GetLatestNewsList")]
        /* UserID,ViewOn*/
        public dynamic GetLatestNewsList(Pro_News objProNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new NewsRepository().GetLatestNewsList(objProNews);

            if (DateList.Count > 0)
                dicto.Add("Result", DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("SetContentSeenByUser")]
        /* UserID,ViewOn*/
        public dynamic SetContentSeenByUser(Pro_News objProNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            int NewsId = Convert.ToInt32(new NewsRepository().SetContentSeenByUser(objProNews));

            if (NewsId > 0)
                dicto.Add("Status", Convert.ToBoolean(1));
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        //[HttpPost]
        //[ActionName("FriendScreen")]
        //public dynamic FriendScreen(Pro_ChatHistoryMaster objProChat)
        //{
        //    Dictionary<string, dynamic> dicto;
        //    var DateList = new ChatHistoryRepository().GetDetailForFriendScreen(objProChat);

        //    if (DateList.Count > 0)
        //        dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Data, StatusConstants.Ok, DateList, "", true);
        //    else
        //    {
        //        dicto = new Dictionary<string, dynamic>();
        //        dicto.Add("Result", "Records not found");
        //        if (Convert.ToString(objProChat.ChatOn) == "1/1/1900 12:00:00 AM")
        //            dicto.Add("Date", new UserRepository().Getdate());
        //    }
        //    return dicto;
        //}

        [HttpPost]
        [ActionName("Truncate")]
        public dynamic Truncate()
        {
            Dictionary<string, dynamic> dicto;
            var detail = new UserRepository().Truncate();

            if (detail)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Truncated data Successfully");
            }
            else
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Truncate fail");
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("SearchUserByName")]
        public dynamic SearchUserByName(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new UserRepository().GetUserBySerachName(User);

            if (DateList.Count > 0)
                dicto.Add("Result", DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("AddAsFriend")]
        public dynamic AddAsFriend(Pro_UserContact User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var Userid = Convert.ToInt32(new UserContactRepository().AddAsFriend(User));
            if (Userid > 0)
            {
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AuthenticateUserForRestore")]
        public dynamic AuthenticateUserForRestore(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto;
            var detail = new UserRepository().RestoreUser(User);

            if (detail == -1)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "ContactNo does not exists");
            }
            else if (detail == -2)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Email does not exists");
            }
            else if (detail == 0)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Email and contact does not exists");
            }
            else
            {
                Random rnd = new Random();
                string code = rnd.Next(1000, 10000).ToString();
                if (code.Length == 3)
                    code = code + "0";
                else if (code.Length == 2)
                    code = code + "00";
                dicto = new Dictionary<string, dynamic>();


                //-------------------Send Email with varfication code--------------
                bool EmailStatus = EmailHelper.SendEmailForVarificationCode(User.EmailId, code, User.ContactNo);
                if (EmailStatus == true)
                {
                    dicto.Add("code", code);
                   // dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("RestoreUser")]
        public dynamic RestoreUser(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserId = new UserRepository().RestoreUser(User);
            if (UserId > 0)
            {
                var UserProfile = new UserRepository().GetUserProfile(UserId);
                var FriendList = new UserContactRepository().GetContactList(UserId);
                if (UserProfile.UserId > 0)
                    dicto.Add("UserDetail", UserProfile);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
                //dicto.Add("RegistrationDate", new UserRepository().Getdate());

                if(FriendList.Count > 0)
                    dicto.Add("FriendList", FriendList);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));

                return dicto;
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("checkForContact")]
        public dynamic checkForContact(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserDetails = new ContactDetailsRepository().checkForContact(user.UserId, user.ContactNo);
            if (UserDetails.UserId > 0)
               dicto.Add("Result",UserDetails);
            else
                dicto.Add("Status", "0");
            return dicto;
        }

        [HttpPost]
        [ActionName("CustomPrivacySetting")]
        public dynamic CustomPrivacySetting(Pro_PrivacySetting user)
        {
            string UserSetting = string.Empty;
            string GroupSetting = string.Empty;
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            Pro_UserPrivacySetting objuser = new Pro_UserPrivacySetting();
            objuser.UserId = user.UserId;
            objuser.PrivacySetting = 2;
            var UserDetail = new UserRepository().UpdatePrivacySetting(objuser);
            if (UserDetail > 0)
            {
                UserSetting = Convert.ToString(user.UserSettingArray);
                GroupSetting = Convert.ToString(user.GroupSettingArray);

                //---User Setting array------------
                JavaScriptSerializer jss = new JavaScriptSerializer();
                List<Pro_UserPrivacySetting_Api> UserSettingList = jss.Deserialize<List<Pro_UserPrivacySetting_Api>>(UserSetting);
                //---End--------------------------

                //---User Setting array------------
                JavaScriptSerializer jss1 = new JavaScriptSerializer();
                List<Pro_GroupPrivacySetting_Api> GroupSettingList = jss1.Deserialize<List<Pro_GroupPrivacySetting_Api>>(GroupSetting);
                //---End--------------------------

                string result = new PrivacySettingRepository().InsertPrivacySetting(UserSettingList, GroupSettingList, user.UserId);
                if (result == "1")
                {
                    dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }
        #endregion

        [HttpPost]
        [ActionName("UploadVideo")]
        public dynamic Upload(Pro_VideoMaster_Api video)
        {
            Dictionary<string, dynamic> dicto;
            // byte[] b = Encoding.ASCII.GetBytes(video.buffer);
            long offset = Convert.ToInt64(video.Offset);
            string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["upload_path"]);
            var IsSuccess = new Helpers.HelperFunctions().UploadFile(video.FileName, video.buffer, offset, path);

            dicto = new Dictionary<string, dynamic>();
            dicto.Add("Result", IsSuccess);
            dicto.Add("Message", (IsSuccess == true ? "Success" : "Failure"));

            return dicto;

        }

        [HttpPost]
        [ActionName("InsertChatWithImageOrVideo1")]
        public dynamic InsertChatWithImageOrVideo1(Pro_ChatHistoryMaster chat)
        {
            string msg = string.Empty;
            bool IsSuccess;
            int chatId = 0;
            Pro_ChatHistoryMaster objchat = new Pro_ChatHistoryMaster();
            Pro_ChatDateDetail Chat = new Pro_ChatDateDetail();
            Pro_GroupChatDateDetail ChatDetail = new Pro_GroupChatDateDetail();
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            long offset = Convert.ToInt64(chat.Offset);
            string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UploadChatImageVideo"]);

            if (chat.Upload == "Image")
                chat.ImagePath = chat.FileName;
            else
                chat.VideoPath = chat.FileName;
            if (chat.IsUploadingEnd == true)
            {
                new Helpers.HelperFunctions().UploadFile(chat.FileName, chat.buffer, offset, path);
                IsSuccess = false;
            }
            else
            {
                IsSuccess = new Helpers.HelperFunctions().UploadFile(chat.FileName, chat.buffer, offset, path);
                dicto.Add("Success", IsSuccess);
            }

            if (IsSuccess == false)
            {
                //--------------Thumb image------------------------------------
                if (chat.Upload == "Image")
                    Helpers.HelperFunctions.SaveThumbImage(path + chat.FileName, 100, 100, "Thumb_");
                //--------------End Thumb image--------------------------------
                //--------------Insert Process----------------------------------
                if (chat.GroupId != 0)
                {
                    ChatDetail = new ChatHistoryRepository().InsertGroupChat(chat);
                    if (ChatDetail.Status == true)
                        dicto.Add("Result", ChatDetail);
                    else
                    {
                        if (File.Exists(path + "/" + chat.FileName))
                            DeleteImageVideo(path + "/" + chat.FileName);
                        if (chat.Upload == "Image")
                            DeleteImageVideo(path + "/" + "Thumb_" + chat.FileName);
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
                else
                {
                    Chat = new ChatHistoryRepository().SaveChat(chat);
                    //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                    if (Chat.ServerID > 0)
                    {
                        dicto.Add("Result", Chat);
                        //dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        if (File.Exists(path + "/" + chat.FileName))
                        {
                            DeleteImageVideo(path + "/" + chat.FileName);
                            if (chat.Upload == "Image")
                                DeleteImageVideo(path + "/" + "Thumb_" + chat.FileName);
                        }
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
            }
            //--------------End Insert Process-------------
            return dicto;
        }

        //[HttpPost]
        //[ActionName("UploadVideo1")]
        //public string UploadVideo1(Pro_VideoMaster_Api1 video)
        //{
        //    //Dictionary<string, dynamic> dicto;
        //    string FilePath=video.File;
        //    int Offset = 0; // starting offset.
        //    int ChunkSize = 65536;

        //    byte[] Buffer = new byte[ChunkSize];
        //    //opening the file for read.
        //    FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
        //    //creating the ServiceSoapClient which will allow to connect to the service.
        //    //WSservice.ServiceSoapClient soap_client = new WSservice.ServiceSoapClient();
        //    try
        //    {
        //        long FileSize = new FileInfo(FilePath).Length; // File size of file being uploaded.
        //        // reading the file.
        //        fs.Position = Offset;
        //        int BytesRead = 0;

        //        while (Offset != FileSize) // continue uploading the file chunks until offset = file size.
        //        {
        //            BytesRead = fs.Read(Buffer, 0, ChunkSize); // read the next chunk
        //            // (if it exists) into the buffer.
        //            // the while loop will terminate if there is nothing left to read
        //            // check if this is the last chunk and resize the buffer as needed
        //            // to avoid sending a mostly empty buffer
        //            // (could be 10Mb of 000000000000s in a large chunk)
        //            if (BytesRead != Buffer.Length)
        //            {
        //                ChunkSize = BytesRead;
        //                byte[] TrimmedBuffer = new byte[BytesRead];
        //                Array.Copy(Buffer, TrimmedBuffer, BytesRead);
        //                Buffer = TrimmedBuffer; // the trimmed buffer should become the new 'buffer'
        //            }
        //            // send this chunk to the server. it is sent as a byte[] parameter,
        //            // but the client and server have been configured to encode byte[] using MTOM.
        //            bool ChunkAppened = new VideoRepository().UploadFile(Path.GetFileName(FilePath), Buffer, Offset);
        //            if (!ChunkAppened)
        //            {
        //                break;
        //            }

        //            // Offset is only updated AFTER a successful send of the bytes.
        //            Offset += BytesRead; // save the offset position for resume
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //    finally
        //    {
        //        fs.Close();
        //    }

        //    return "Success";

        //}

        [HttpPost]
        [ActionName("InsertComment")] //for on and of
        public dynamic InsertComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var CommentId = new CommentMasterRepository().SaveComment(Comment);

            if (Convert.ToInt32(CommentId) > 0)
            {
               // dicto.Add("CommentId", Convert.ToInt32(CommentId));
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertLike")] //for on and of
        public dynamic InsertLike(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeId = new LikeMasterRepository().SaveLike(Like);

            if (Convert.ToInt32(LikeId) > 0)
            {
                //dicto.Add("LikeId", Convert.ToInt32(LikeId));
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("DeleteComment")] //for on and of
        public dynamic DeleteComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var CommentId = new CommentMasterRepository().DeleteComment(Comment.CommentId);

            if (Convert.ToInt32(CommentId) > 0)
            {
                dicto.Add("CommentId", Convert.ToInt32(CommentId));
                //dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("DeleteLike")] //for on and of
        public dynamic DeleteLike(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeId = new LikeMasterRepository().DeleteLike(Like.LikeId);

            if (Convert.ToInt32(LikeId) > 0)
            {
                dicto.Add("LikeId", Convert.ToInt32(LikeId));
                //dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }


        [HttpPost]
        [ActionName("GetComment")] //for on and of
        public dynamic GetComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CommentList = new CommentMasterRepository().GetComment(Comment);

            if (CommentList.Count > 0)
                dicto.Add("Result", CommentList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("GetLikeCount")] //for on and of
        public dynamic GetLikeCount(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeCount = new LikeMasterRepository().GetLikeCount(Like);

            if (LikeCount > 0)
                dicto.Add("LikeCount", LikeCount);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetRecentMsg")]
        public dynamic GetRecentMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>(); ;
            List<Pro_FriendScreen_Api> chats = new ChatHistoryRepository().GetRecentMsg(Chat);
            if (chats.Count > 0)
            {
                dicto.Add("Result", chats);
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        //-------Add by Nirmal 7-01-2013-------
        [HttpPost]
        [ActionName("GetHighlightedContent")] //for send total like count and other information
        public dynamic GetLikeCount(Pro_LikesMaster objlikes)
        {
            const int pageSize = 10;
            int count = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var TotalLikecount = new LikeMasterRepository().GetAllLikesCount(objlikes.RecordIndex, objlikes.ContentType);
            if (TotalLikecount.Count > 0)
            {
                dicto.Add("Result", TotalLikecount);
                if (TotalLikecount.Count < pageSize || ((objlikes.RecordIndex + pageSize) == count))
                {
                    dicto.Add("Count", TotalLikecount.Count);
                    dicto.Add("Next", false);
                }
                else
                {
                    dicto.Add("Count", TotalLikecount.Count);
                    dicto.Add("Next", true);
                }
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedComments")]
        public dynamic GetComments(Pro_CommentsMaster objcomments)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var TotalComments = new LikeMasterRepository().GetAllComments(objcomments.ContentId, objcomments.ContentType);
            if (TotalComments.Count > 0)
            {
                dicto.Add("Result", TotalComments);
                dicto.Add("Count", TotalComments.Count);
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        //------------End-----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Gammers.Models;
using Gammers.Repository;
using Gammers.Helpers;
using System.Web.Optimization;
using System.Threading.Tasks;
using System.Web;
using System.IO;
using System.Drawing;
using System.ComponentModel;
using System.Web.Hosting;
using System.Drawing.Imaging;
using System.Net.Http.Headers;
using System.Diagnostics;
using HoiioSDK.NET;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Globalization;
using System.Data;

namespace Gammers.Controllers
{
    public class UserController : ApiController
    {

        [HttpPost]
        [ActionName("AuthenticateUser")]
        public dynamic AuthenticateUser(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            var Result = Convert.ToInt32(new UserRepository().AuthentucateUser(user.EmailId, user.ContactNo));
            if (Result == -1)
                dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Error, StatusConstants.Error, null, "Email does not exists."); // msg as per client said
            else if (Result == -2)
                dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Error, StatusConstants.Error, null, "Contact does not exists."); //msg as per client said
            else
            {
                Random rnd = new Random();
                string code = rnd.Next(1000, 10000).ToString();
                if (code.Length == 3)
                    code = code + "0";
                else if (code.Length == 2)
                    code = code + "00";
                dicto = new Dictionary<string, dynamic>();


                //-------------------Send Email with varfication code--------------
                bool EmailStatus = EmailHelper.SendEmailForVarificationCode(user.EmailId, code, user.ContactNo);
                if (EmailStatus == true)
                {
                    dicto.Add("code", code);
                    dicto.Add("Result", "Email Send Successfully");
                }
                else
                    dicto.Add("Result", "Email Sending fail");
                //-------------------End-------------------------------------------
            }
            return dicto;
        }

        private int GetTempId(string emailid)
        {
            if (emailid == Convert.ToString("VGarha@gmail.com").ToLower())
                return 1;
            else if (emailid == Convert.ToString("MiMart187@gmail.com").ToLower())
                return 2;
            else if (emailid == Convert.ToString("Geena6992@gmail.com").ToLower())
                return 3;
            else if (emailid == Convert.ToString("dipen.panchasara@ifuturz.com").ToLower())
                return 4;
            else if (emailid == Convert.ToString("mukesh.verma@ifuturz.com").ToLower())
                return 5;
            else if (emailid == Convert.ToString("rajan.samouker@ifuturz.com").ToLower())
                return 6;
            else
                return 0;
        }

        [HttpPost]
        [ActionName("RegisterUser")]
        public dynamic RegisterUser(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            user.DeviceId = user.DeviceId.Replace(" ","");
            Pro_UserDetail Userdetail = new UserRepository().InsertUser(user);
            if (Userdetail.UserId > 0)
            {
                dicto.Add("Message", Userdetail.Message);
                dicto.Add("UserId", Userdetail.UserId);
                dicto.Add("CreatedOn", Userdetail.CreatedOn);
            }
            else
            {
                dicto.Add("Message", Userdetail.Message);
                dicto.Add("UserId", Userdetail.UserId);
                dicto.Add("CreatedOn", Userdetail.CreatedOn);
            }
         
            return dicto;
        }

        [HttpPost]
        [ActionName("RefreshContacts")]
        public dynamic RefreshContacts(Pro_ContactDetails user)
        {
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            i = Convert.ToInt32(new ContactDetailsRepository().UpdateIsFriend(user.UserId, user.CreatedOn));

            if (i == 1)
            {
                var ContactDetails = new ContactDetailsRepository().GetFriendList(user.UserId, user.CreatedOn);
                if (ContactDetails.Count > 0)
                    dicto.Add("Result", ContactDetails);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertContactDetails")]
        public dynamic InsertContactDetails(Pro_ContactDetails user)
        {
            string contacts = string.Empty;
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            contacts = Convert.ToString(user.ContactArray);
            JavaScriptSerializer jss = new JavaScriptSerializer();
            List<Pro_ContactDetails_Api> Contactlist = jss.Deserialize<List<Pro_ContactDetails_Api>>(contacts);
            string result = new ContactDetailsRepository().InsertContacts(Contactlist, user.UserId, user.CreatedOn);
            if (result == "Success")
            {
                i = Convert.ToInt32(new ContactDetailsRepository().UpdateIsFriend(user.UserId, user.CreatedOn));
            }
            if (i == 1)
            {
                var ContactDetails = new ContactDetailsRepository().GetFriendList(user.UserId, user.CreatedOn);
                if (ContactDetails != null)
                    dicto.Add("Result", ContactDetails);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("RestoreFriendList")]
        public dynamic RestoreFriendList(Pro_FriendsContactDetails_Api user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetails = new ContactDetailsRepository().RestoreFriendList(Convert.ToInt32(user.UserId));
            if (UserDetails.Count > 0)
                dicto.Add("Result", UserDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetFeaturedMember")]
        public dynamic GetFeaturedMember(Pro_UserMaster_Api user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetails = new UserRepository().GetFeaturedMember(user.UserId);
            if (UserDetails.UserId > 0)
                dicto.Add("Result", UserDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedPicture")]
        public dynamic GetHighlightedPicture(Pro_PictureShareMaster_Api Picture)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var PictureDetails = new PictureShareRepository().GetTotalSharePicture(Picture.UserId);
            if (PictureDetails.Count > 0)
                dicto.Add("Result", PictureDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedVideos")]
        public dynamic GetHighlightedVideos(Pro_VideoShareMaster_Api Video)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var VideoDetails = new VideoShareRepository().GetTotalShareVideos(Video.UserId);
            if (VideoDetails.Count > 0)
                dicto.Add("Result", VideoDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetUserContactDetails")]
        public dynamic GetUserContactDetails(Pro_UserContact user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserContactDetails = new UserContactRepository().GetUserContactDetails(user.UserId, user.Flag);
            if (UserContactDetails.Count > 0)
                dicto.Add("Result", UserContactDetails);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetUserProfile")]
        public dynamic GetUserProfile(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserProfile = new UserRepository().GetUserProfile(user.UserId);

            if (UserProfile.UserId > 0)
                dicto.Add("Result",UserProfile);
            else
                dicto.Add("Status",Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("UpdateProfileAndProfilePic")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> UpdateProfileAndProfilePic()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var user = new Pro_UserMaster();
            bool Status = false;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/ProfilePicture");
            var provider = new MultipartFormDataStreamProvider(root);

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "UserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.UserId = Convert.ToInt32(val);
                                }
                                if (string.Equals(key, "UserName", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.UserName = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Sex", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Sex = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Birthdate", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Birthdate = Convert.ToDateTime(val);
                                }
                                else if (string.Equals(key, "AboutYou", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.AboutYou = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Intrestes", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Intrestes = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Hobbies", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Hobbies = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "Favoritemovies", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.Favoritemovies = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "LookingFor", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        user.LookingFor = Convert.ToString(val);
                                }
                                break;
                            }
                    }

                    if (user.UserId > 0)
                    {
                        if (provider.FileData.Count != 0)
                        {
                            string OldPic = new UserRepository().GetProfilePic(user.UserId);
                            if (!string.IsNullOrEmpty(OldPic))
                            {
                                if (File.Exists(root + "/" + OldPic))
                                {
                                    File.Delete(root + "/" + OldPic);
                                    File.Delete(root + "/" + "Thumb_" + OldPic);
                                }
                            }
                            //var ProfilePic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + user.UserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                            //var ProfilePic = "ProfilePic_" + user.UserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                            var ProfilePic = "ProfilePic_" + user.UserId + ".png";
                            var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                            var img = System.Drawing.Image.FromFile(finfo.FullName);
                            //img = Helpers.ImageExtensions.Resize(img, Width, Height);
                            var converter = new System.Drawing.ImageConverter();
                            var b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                            user.ProfilePic = ProfilePic;
                            user.Mode = "UpdateProfilePic";
                            int retval = Convert.ToInt32(new UserRepository().SaveProfile(user));
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, ProfilePic), img.Width, img.Height);
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + ProfilePic), 100, 100);
                            img.Dispose();
                            Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                            //System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, userImage));
                            if (retval == 0)
                            {
                                if (File.Exists(root + "/" + ProfilePic))
                                {
                                    File.Delete(root + "/" + ProfilePic);
                                    File.Delete(root + "/" + "Thumb_" + ProfilePic);
                                }
                                Status =Convert.ToBoolean(0);
                            }
                        }

                        user.Mode = "UpdateProfile";
                        int Returnval = Convert.ToInt32(new UserRepository().SaveProfile(user));
                        if (Returnval > 0)
                            Status = Convert.ToBoolean(1);
                        else
                            Status = Convert.ToBoolean(0);

                    }
                    Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
                    dicto.Add("Status", Status);
                    return dicto;
                   // return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, Status);
                }
            );
            return task;
        }

        public dynamic GetVideo(int id)
        {
            Pro_VideoMaster objpicture = new Pro_VideoMaster();
            objpicture = new VideoRepository().GetVideoById(id);
            byte[] Content = objpicture.VideoContent;
            //MemoryStream ms = new MemoryStream(Content);

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(Content);
            object rval = formatter.Deserialize(stream);
            stream.Close();
            return rval;
        }

        //public HttpResponseMessage Get(int id)
        //{
        //    Pro_PictureMaster objpicture = new Pro_PictureMaster();
        //    objpicture = new PictureRepository().GetPictureById(id);
        //    byte[] imgData = objpicture.ImageContent;
        //    MemoryStream ms = new MemoryStream(imgData);
        //    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        //    response.Content = new StreamContent(ms);
        //    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");

        //    return response;
        //}
        [HttpPost]
        [ActionName("InsertChat")]
        public dynamic InsertChat(Pro_ChatHistoryMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto;
            if (chatHistory.GroupId != 0)
            {
                Pro_GroupChatDateDetail chat = new ChatHistoryRepository().InsertGroupChat(chatHistory);
                dicto = new Dictionary<string, dynamic>();
                if (chat.Status == true)
                {
                    //dicto.Add("ChatId", ChatId);
                    dicto.Add("Result", chat);
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                Pro_ChatDateDetail Chat = new ChatHistoryRepository().SaveChat(chatHistory);
                dicto = new Dictionary<string, dynamic>();
                if (Chat.ServerID > 0)
                {
                    dicto.Add("Result", Chat);
                    //dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                {
                    dicto.Add("Status", Convert.ToBoolean(0));
                }
            }

            return dicto;

        }

        [HttpPost]
        [ActionName("InsertChatwithImageOrVideo")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> InsertChatwithImageOrVideo()
        {
            HttpRequestMessage request = Request;
            Pro_GroupChatDateDetail chatdetail = new Pro_GroupChatDateDetail();
            Pro_ChatDateDetail Chat = new Pro_ChatDateDetail();
            int Height = 0;
            int Width = 0;
            string Upload = string.Empty;
            string FileName = string.Empty;
            byte[] buffer = null;
            long offset = 0;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var chathistory = new Pro_ChatHistoryMaster();
            string strmsg = string.Empty;
            //var root =Helpers.ConstantValues.RootUrl;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/ChatHistory");
            var provider = new MultipartFormDataStreamProvider(root);
            Dictionary<string, dynamic> dicto = null;
            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "FromId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.FromId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ToId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.ToId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "GroupId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        chathistory.GroupId = Convert.ToInt32(val);
                                }
                                //else if (string.Equals(key, "ChatOn", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        chathistory.ChatOn = Convert.ToDateTime(val);
                                //}
                                else if (string.Equals(key, "Upload", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        Upload = val;
                                }
                                //else if (string.Equals(key, "FileName", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        FileName = val;
                                //}
                                //else if (string.Equals(key, "buffer", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        buffer = Encoding.ASCII.GetBytes(val);
                                //}
                                //else if (string.Equals(key, "Offset", StringComparison.OrdinalIgnoreCase))
                                //{
                                //    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                //        offset =  Convert.ToInt64(val);
                                //}
                                break;
                            }
                    }

                    if (Upload == "Image")
                    {
                        var chatId = 0;
                        string msg = string.Empty;

                        //var userImage = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                        var userImage = Helpers.HelperFunctions.CreateUniqueFileName() + ".png";
                        chathistory.ImagePath = userImage;

                        var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                        var img = System.Drawing.Image.FromFile(finfo.FullName);
                        //img = Helpers.ImageExtensions.Resize(img, Width, Height);

                        var converter = new System.Drawing.ImageConverter();
                        var b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                        bool retval = Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, userImage), img.Width, img.Height);

                        img.Dispose();
                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                        dicto = new Dictionary<string, dynamic>();
                        if (retval)
                        {
                            Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + userImage), 100, 100);
                            if (chathistory.GroupId != 0)
                            {
                                chatdetail = new ChatHistoryRepository().InsertGroupChat(chathistory);
                                if (chatdetail.Status == true)
                                {
                                    dicto.Add("Result", chatdetail);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + userImage))
                                        DeleteImageVideo(root + "/" + userImage);
                                    dicto.Add("Message", msg);
                                }
                            }
                            else
                            {
                                Chat = new ChatHistoryRepository().SaveChat(chathistory);
                                //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                                if (Chat.ServerID > 0)
                                {
                                    dicto.Add("Result", Chat);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + userImage))
                                    {
                                        DeleteImageVideo(root + "/" + userImage);
                                        DeleteImageVideo(root + "/" + userImage + "_Thumb");
                                    }
                                    dicto.Add("Message", "File Upload fail");
                                }
                            }
                        }
                        else
                        {
                            dicto.Add("Message", "File Uploaded Fail.");
                        }
                    }
                    else
                    {
                        dicto = new Dictionary<string, dynamic>();
                        string msg = string.Empty;
                        var UserVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                        chathistory.VideoPath = UserVideo;

                        var finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, UserVideo));
                        if (File.Exists(root + "/" + UserVideo))
                        {
                            if (chathistory.GroupId != 0)
                            {
                                chatdetail = new ChatHistoryRepository().InsertGroupChat(chathistory);
                                if (chatdetail.Status == true)
                                {
                                    dicto.Add("Result", chatdetail);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + UserVideo))
                                        DeleteImageVideo(root + "/" + UserVideo);
                                    dicto.Add("Message", msg);
                                }
                            }
                            else
                            {
                                Chat = new ChatHistoryRepository().SaveChat(chathistory);
                                //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                                if (Chat.ServerID > 0)
                                {
                                    dicto.Add("Result", Chat);
                                    dicto.Add("Message", "File Uploaded Successfully");
                                }
                                else
                                {
                                    if (File.Exists(root + "/" + UserVideo))
                                        DeleteImageVideo(root + "/" + UserVideo);
                                    dicto.Add("Message", "File Upload fail");
                                }
                            }
                        }

                    }

                    return dicto;
                    //return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        public void DeleteImageVideo(string FilePath)
        {
            File.Delete(FilePath);
        }

        [HttpPost]
        [ActionName("GetMyNewMsg")]
        public dynamic GetMyNewMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_ChatHistoryDetail> chats = new ChatHistoryRepository().GetMyNewMsg(Chat.FromId, Chat.ToId, Chat.ChatDate);
            Pro_Status Status = new UserRepository().GetUserStatus(Chat.FromId,Chat.ChatId);

            if (chats.Count > 0)
            {
                dicto.Add("Result", chats);
                dicto.Add("IsOnline", Status.IsOnline);
                dicto.Add("IsTyping", Status.IsTyping);
            }
            else
            {
                dicto.Add("IsOnline", Status.IsOnline);
                dicto.Add("IsTyping", Status.IsTyping);
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("GetGroupChatHistory")]
        public dynamic GetGroupChatHistory(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_GroupChatHistoryDetail> chats = new ChatHistoryRepository().GetGroupChatHistory(Chat.ToId, Chat.GroupId);
            if (chats.Count > 0)
                dicto.Add("Result", chats);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetMyNewGroupMsg")]
        public dynamic GetMyNewGroupMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            List<Pro_GroupChatHistoryDetail> chats = new ChatHistoryRepository().GetMyNewGroupMsg(Chat.ToId, Chat.GroupId, Chat.ChatDate);
            if (chats.Count > 0)
                dicto.Add("Result", chats);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertGroup")]
        public dynamic InsertGroup(Pro_GroupMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            if (chatHistory.ListofUsers != null)
            {
                chatHistory.CreatedOn = DateTime.UtcNow;
                int GroupId = Convert.ToInt32(new GroupRepository().SaveGroup(chatHistory));
                if (GroupId > 0)
                    dicto.Add("GroupId", GroupId);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetAllGroupsByUserId")]
        public dynamic GetAllGroupsByUserId(int UserId)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserGroups = new GroupRepository().GetAllGroupsByUserId(UserId);
            if (UserGroups != null)
               dicto.Add("Result", UserGroups);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetGroupsByGroupId")]
        public dynamic GetGroupsByGroupId(int GroupId)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var groupsDetail = new GroupRepository().GetGroupsByGroupId(GroupId);

            if (groupsDetail != null)
                dicto.Add("Result", groupsDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("GetAllGroupUser")]
        public dynamic GetAllGroupUser(Pro_GroupMaster chatHistory)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var groupsDetail = new GroupRepository().GetAllGroupUser(chatHistory.GroupId);

            if (groupsDetail != null)
               dicto.Add("Result", groupsDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        #region Webposter current

        [HttpPost]
        [ActionName("AddToWebPoster1")]
        public dynamic AddToWebPoster1(Pro_WebPoster objWebPoster)
        {
            string strmsg = string.Empty;
            bool IsDataRemain;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            if (objWebPoster.Share == 0)
            {
                long offset = Convert.ToInt64(objWebPoster.Offset);
                string path = string.Empty;
                if (objWebPoster.FromCommunity == true)
                    path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["CommunityUrl"]);
                else
                    path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WebPosterUrl"]);

                if (objWebPoster.ContentType == "Image")
                    objWebPoster.ChatImgName = objWebPoster.FileName;
                else
                    objWebPoster.ChatVideoName = objWebPoster.FileName;
                if (objWebPoster.IsUploadingEnd == true)
                {
                    new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    IsDataRemain = false;
                }
                else
                {
                    IsDataRemain = new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    dicto.Add("Success", IsDataRemain);
                }
                if (IsDataRemain == false)
                {
                    if (objWebPoster.ContentType == "Image")
                    {
                        //--------------Thumb image------------------------------------
                        if (objWebPoster.ContentType == "Image")
                            Helpers.HelperFunctions.SaveThumbImage(path + objWebPoster.FileName, 100, 100, "Thumb_");
                        //--------------End Thumb image--------------------------------


                        int pictureId = Convert.ToInt32(new PictureRepository().SaveUserPicture(objWebPoster.LoginUserId, objWebPoster.ChatImgName, Convert.ToDateTime(objWebPoster.CreatedOn), objWebPoster.FromCommunity));
                        if (pictureId > 0)
                        {
                            if (objWebPoster.FromCommunity == true)
                            {
                                dicto.Add("Status", Convert.ToBoolean(1));
                                dicto.Add("ContentId", pictureId);
                            }
                            else
                                dicto.Add("Status", Convert.ToBoolean(1));
                        }
                        else
                        {
                            if (File.Exists(path + "/" + objWebPoster.FileName))
                            {
                                DeleteImageVideo(path + "/" + objWebPoster.FileName);
                                DeleteImageVideo(path + "/" + "Thumb_" + objWebPoster.FileName);
                            }
                            dicto.Add("Status", Convert.ToBoolean(0));
                        }

                    }
                    else
                    {

                        int VideoId = Convert.ToInt32(new VideoRepository().SaveUserVideo(objWebPoster.LoginUserId, objWebPoster.ChatVideoName, Convert.ToDateTime(objWebPoster.CreatedOn), objWebPoster.FromCommunity));
                        if (VideoId > 0)
                        {
                            if (objWebPoster.FromCommunity == true)
                            {
                                dicto.Add("Status", Convert.ToBoolean(1));
                                dicto.Add("ContentId", VideoId);
                            }
                            else
                                dicto.Add("Status", Convert.ToBoolean(1));
                        }
                        else
                        {
                            if (File.Exists(path + "/" + objWebPoster.FileName))
                            {
                                DeleteImageVideo(path + "/" + objWebPoster.FileName);
                            }
                            dicto.Add("Status", Convert.ToBoolean(0));
                        }
                    }
                }
            }
            else //---If Share
            {
                if (objWebPoster.ContentType == "Image")
                {
                    Pro_PictureShareMaster objPictureShare = new Pro_PictureShareMaster();
                    objPictureShare.UserId = objWebPoster.LoginUserId;
                    objPictureShare.PictureId = objWebPoster.ContentId;
                    objPictureShare.ShareId = objWebPoster.FromUserId;
                    objPictureShare.CreatedOn = objWebPoster.CreatedOn;
                    objPictureShare.FromCommunity = objWebPoster.FromCommunity;
                    int pictureShareId = Convert.ToInt32(new PictureShareRepository().SaveSharePicture(objPictureShare));
                    if (pictureShareId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
                else
                {
                    Pro_VideoShareMaster objVideoShare = new Pro_VideoShareMaster();
                    objVideoShare.UserId = objWebPoster.LoginUserId;
                    objVideoShare.VideoId = objWebPoster.ContentId;
                    objVideoShare.CreatedOn = DateTime.UtcNow.ToString();
                    objVideoShare.ShareId = objWebPoster.FromUserId;
                    objVideoShare.FromCommunity = objWebPoster.FromCommunity;
                    int VideoShareId = Convert.ToInt32(new VideoShareRepository().SaveShareVideo(objVideoShare));
                    if (VideoShareId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AddToWebPoster")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> AddToWebPoster()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var webposter = new Pro_WebPoster();
            string strmsg = string.Empty;
            string ContentType = string.Empty;
            string strChatContent = string.Empty;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/WebPoster");
            var provider = new MultipartFormDataStreamProvider(root);

            Image img = null;
            byte[] b = null;
            System.IO.FileInfo finfo = null;
            var webposterPic = "";
            var webposterVideo = "";

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "Share", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.Share = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "LoginUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.LoginUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "FromUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ContentType", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        ContentType = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "ContentId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.ContentId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "CreatedOn", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.CreatedOn = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "FromCommuniy", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromCommunity = Convert.ToBoolean(val);
                                }
                                break;
                            }
                    }

                    if (webposter.LoginUserId > 0)
                    {
                        if (webposter.Share == 0)
                        {
                            if (provider.FileData.Count != 0)
                            {
                                if (ContentType == "Image")
                                {
                                    //webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + ".png";
                                    finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                    img = System.Drawing.Image.FromFile(finfo.FullName);
                                    var converter = new System.Drawing.ImageConverter();
                                    b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                                    webposter.WebposterImg = webposterPic;
                                    DateTime dt = DateTime.UtcNow;
                                    //DateTime dt = Convert.ToDateTime(webposter.CreatedOn);
                                    int pictureId = Convert.ToInt32(new PictureRepository().SaveUserPicture(webposter.LoginUserId, webposterPic, dt, webposter.FromCommunity));

                                    if (pictureId > 0)
                                    {
                                        //----Image upload-----
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, webposterPic), img.Width, img.Height);
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + webposterPic), 100, 100);
                                        img.Dispose();
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End Image upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                                else if (ContentType == "Video")
                                {
                                    webposterVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposter.WebposterVideo = webposterVideo;
                                    DateTime dt = DateTime.UtcNow;
                                    int VideoId = Convert.ToInt32(new VideoRepository().SaveUserVideo(webposter.LoginUserId, webposterVideo, dt, webposter.FromCommunity));
                                    if (VideoId > 0)
                                    {
                                        //----video upload-----
                                        finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, webposterVideo));
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End video upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                            }
                        }
                        else
                        {
                            if (ContentType == "Image")
                            {
                                Pro_PictureShareMaster objPictureShare = new Pro_PictureShareMaster();
                                objPictureShare.UserId = webposter.LoginUserId;
                                objPictureShare.PictureId = webposter.ContentId;
                                objPictureShare.CreatedOn = DateTime.UtcNow.ToString();
                                objPictureShare.ShareId = webposter.FromUserId;
                                int pictureShareId = Convert.ToInt32(new PictureShareRepository().SaveSharePicture(objPictureShare));
                                if (pictureShareId > 0)
                                    strmsg = "1";
                                else
                                    strmsg = "0";
                            }
                            else if (ContentType == "Video")
                            {
                                Pro_VideoShareMaster objVideoShare = new Pro_VideoShareMaster();
                                objVideoShare.UserId = webposter.LoginUserId;
                                objVideoShare.VideoId = webposter.ContentId;
                                objVideoShare.CreatedOn = DateTime.UtcNow.ToString();
                                objVideoShare.ShareId = webposter.FromUserId;
                                int VideoShareId = Convert.ToInt32(new VideoShareRepository().SaveShareVideo(objVideoShare));
                                if (VideoShareId > 0)
                                    strmsg = "1";
                                else
                                    strmsg = "0";
                            }
                        }
                    }
                    return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        [HttpPost]
        [ActionName("AddChatToWebPoster1")]
        public dynamic AddChatToWebPoster1(Pro_WebPoster objWebPoster)
        {
            string msg = string.Empty;
            bool IsSuccess;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();


            if (objWebPoster.Share == 0)
            {
                long offset = Convert.ToInt64(objWebPoster.Offset);
                string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WebPosterUrl"]);
                if (objWebPoster.ContentType == "Image")
                    objWebPoster.ChatImgName = objWebPoster.FileName;
                else
                    objWebPoster.ChatVideoName = objWebPoster.FileName;
                if (objWebPoster.IsUploadingEnd == true)
                {
                    new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    IsSuccess = false;
                }
                else
                {
                    IsSuccess = new Helpers.HelperFunctions().UploadFile(objWebPoster.FileName, objWebPoster.buffer, offset, path);
                    dicto.Add("Success", IsSuccess);
                }

                if (IsSuccess == false)
                {
                    Pro_webPosterChat objchat = new Pro_webPosterChat();
                    objchat.FromId = objWebPoster.LoginUserId;
                    objchat.ToId = objWebPoster.FromUserId;
                    objchat.GroupId = 0;
                    objchat.ChatOn = objWebPoster.CreatedOn;
                    if (objWebPoster.ContentType == "Image")
                    {
                        objchat.ContentType = "ChatImage";
                        objchat.Content = objWebPoster.ChatImgName;
                        //--------------Thumb image------------------------------------
                        if (objWebPoster.ContentType == "Image")
                            Helpers.HelperFunctions.SaveThumbImage(path + objWebPoster.FileName, 100, 100, "Thumb_");
                        //--------------End Thumb image--------------------------------
                    }
                    else if (objWebPoster.ContentType == "Video")
                    {
                        objchat.ContentType = "ChatVideo";
                        objchat.Content = objWebPoster.ChatVideoName;
                    }
                    else
                    {
                        objchat.ContentType = "ChatText";
                        objchat.Content = objWebPoster.TextMsg;
                    }

                    int webPosterId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                    if (webPosterId > 0)
                    {
                        dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        if (File.Exists(path + "/" + objWebPoster.FileName))
                        {
                            DeleteImageVideo(path + "/" + objWebPoster.FileName);
                            if (objchat.ContentType == "ChatImage")
                                DeleteImageVideo(path + "/" + "Thumb_" + objWebPoster.FileName);
                        }
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }

                }
            }
            else
            {
                Pro_WebPosterChatShare chatshare = new Pro_WebPosterChatShare();
                chatshare.UserId = objWebPoster.LoginUserId;
                chatshare.WPChatId = objWebPoster.ContentId;
                chatshare.ShareId = objWebPoster.FromUserId;
                chatshare.CreatedOn = objWebPoster.CreatedOn;
                int ChatId = Convert.ToInt32(new WebPosterChatShareRepository().SaveShareChat(chatshare));
                if (ChatId > 0)
                {
                    dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AddChatToWebPoster")]
        public System.Threading.Tasks.Task<Dictionary<string, dynamic>> AddChatToWebPoster()
        {
            HttpRequestMessage request = Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            var webposter = new Pro_WebPoster();
            string strmsg = string.Empty;
            string ContentType = string.Empty;
            string strChatContent = string.Empty;
            var root = HttpContext.Current.Server.MapPath("~/Uploads/WebPoster");
            var provider = new MultipartFormDataStreamProvider(root);

            Image img = null;
            byte[] b = null;
            System.IO.FileInfo finfo = null;
            var webposterPic = "";
            var webposterVideo = "";

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith(o =>
                {
                    foreach (var key in provider.FormData.AllKeys)
                    {
                        var values = provider.FormData.GetValues(key);
                        if (values != null)
                            foreach (var val in values)
                            {
                                if (string.Equals(key, "Share", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.Share = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "LoginUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.LoginUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "FromUserId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.FromUserId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "ContentType", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        ContentType = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "ContentId", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.ContentId = Convert.ToInt32(val);
                                }
                                else if (string.Equals(key, "TextMsg", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        strChatContent = Convert.ToString(val);
                                }
                                else if (string.Equals(key, "CreatedOn", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!string.IsNullOrEmpty(Convert.ToString(val)))
                                        webposter.CreatedOn = Convert.ToString(val);
                                }
                                break;
                            }
                    }

                    if (webposter.LoginUserId > 0)
                    {
                        if (webposter.Share == 0)
                        {
                            Pro_webPosterChat objchat = new Pro_webPosterChat();
                            objchat.FromId = webposter.LoginUserId;
                            objchat.ToId = webposter.FromUserId;
                            objchat.GroupId = 0;
                            objchat.ChatOn = DateTime.UtcNow.ToString();
                            if (provider.FileData.Count != 0)
                            {
                                if (ContentType == "Image")
                                {
                                    //webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    webposterPic = Helpers.HelperFunctions.CreateUniqueFileName() + "_" + webposter.LoginUserId + ".png";
                                    finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                    img = System.Drawing.Image.FromFile(finfo.FullName);
                                    var converter = new System.Drawing.ImageConverter();
                                    b = (byte[])converter.ConvertTo(img, typeof(byte[]));
                                    //DateTime dt = Convert.ToDateTime(webposter.CreatedOn);
                                    objchat.ContentType = "ChatImage";
                                    objchat.Content = webposterPic;
                                    int pictureId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));

                                    if (pictureId > 0)
                                    {
                                        //----Image upload-----
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, webposterPic), img.Width, img.Height);
                                        Helpers.HelperFunctions.SaveFile(b, System.IO.Path.Combine(root, "Thumb_" + webposterPic), 100, 100);
                                        img.Dispose();
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End Image upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                                else if (ContentType == "Video")
                                {
                                    webposterVideo = Helpers.HelperFunctions.CreateUniqueFileName() + System.IO.Path.GetExtension(provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", ""));
                                    DateTime dt = DateTime.UtcNow;
                                    objchat.ContentType = "ChatVideo";
                                    objchat.Content = webposterVideo;
                                    int VideoId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                                    if (VideoId > 0)
                                    {
                                        //----video upload-----
                                        finfo = new System.IO.FileInfo(provider.FileData.First().LocalFileName);
                                        System.IO.File.Move(finfo.FullName, System.IO.Path.Combine(root, webposterVideo));
                                        Helpers.HelperFunctions.DeleteFile(finfo.FullName);
                                        strmsg = "1";
                                        //----End video upload-----
                                    }
                                    else
                                        strmsg = "0";
                                }
                            }
                            if (ContentType == "TextMsg")
                            {
                                objchat.ContentType = "ChatText";
                                objchat.Content = strChatContent;
                                int ChatId = Convert.ToInt32(new WebPosterChatRepository().SavewebPosterChat(objchat));
                                if (ChatId > 0)
                                {
                                    strmsg = "1";
                                }
                                else
                                    strmsg = "0";
                            }
                        }
                        else
                        {
                            Pro_WebPosterChatShare chatshare = new Pro_WebPosterChatShare();
                            chatshare.UserId = webposter.LoginUserId;
                            chatshare.WPChatId = webposter.ContentId;
                            chatshare.ShareId = webposter.FromUserId;
                            chatshare.CreatedOn = DateTime.UtcNow.ToString();
                            int ChatId = Convert.ToInt32(new WebPosterChatShareRepository().SaveShareChat(chatshare));
                            if (ChatId > 0)
                            {
                                strmsg = "1";
                            }
                            else
                                strmsg = "0";
                        }
                    }
                    return ServiceHelper.GetServiceJson(ServiceHelper.JsonType.ResultMessage, StatusConstants.Ok, strmsg);
                }
            );
            return task;
        }

        [HttpPost]
        [ActionName("GetDatesForWebposter")]
        public dynamic GetDatesForWebposter(Pro_WebPoster objPro_WebPoster)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new WebPosterRepository().GetDatesForWebPoster(objPro_WebPoster);

            if (DateList.Count > 0)
            {
                if(DateList[0] == "2")
                    dicto.Add("Status", Convert.ToInt32(DateList[0]));
                else
                    dicto.Add("Result", DateList);
            }
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetDetailsForWebPoster")]
        public dynamic GetDetailsForWebPoster(Pro_WebPoster objProWebPoster)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new WebPosterRepository().GetDetailsForWebPosterByDate(objProWebPoster);

            if (DateList.Count > 0)
                dicto.Add("Result",DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("WelcomeHome")]
        public dynamic WelcomeHome(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CountDetail = new UserRepository().InsertLatLongAndUserStatus(user);

            if (user.UserId > 0)
                dicto.Add("Result",CountDetail);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }


        [HttpPost]
        [ActionName("UserStatus")]
        public dynamic UserStatus(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CountDetail = new UserRepository().UserStatus(user);

            if (CountDetail > 0)
                 dicto.Add("Result",CountDetail);
            else
                 dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("UserPrivacySetting")] //for on and of
        public dynamic UserPrivacySetting(Pro_UserPrivacySetting user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var UserDetail = new UserRepository().UpdatePrivacySetting(user);

            if (UserDetail > 0)
                dicto.Add("Status", Convert.ToBoolean(1));
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }
        #endregion


        #region News

        [HttpPost]
        [ActionName("GetNewsCount")]
        public dynamic GetNewsCount(Pro_News objNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var newsCount = new NewsRepository().GetNewsCount(objNews);

            if (newsCount > 0)
                dicto.Add("Result",newsCount);
            else
                 dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }


        [HttpPost]
        [ActionName("GetLatestNewsList")]
        /* UserID,ViewOn*/
        public dynamic GetLatestNewsList(Pro_News objProNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new NewsRepository().GetLatestNewsList(objProNews);

            if (DateList.Count > 0)
                dicto.Add("Result", DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("SetContentSeenByUser")]
        /* UserID,ViewOn*/
        public dynamic SetContentSeenByUser(Pro_News objProNews)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            int NewsId = Convert.ToInt32(new NewsRepository().SetContentSeenByUser(objProNews));

            if (NewsId > 0)
                dicto.Add("Status", Convert.ToBoolean(1));
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        //[HttpPost]
        //[ActionName("FriendScreen")]
        //public dynamic FriendScreen(Pro_ChatHistoryMaster objProChat)
        //{
        //    Dictionary<string, dynamic> dicto;
        //    var DateList = new ChatHistoryRepository().GetDetailForFriendScreen(objProChat);

        //    if (DateList.Count > 0)
        //        dicto = ServiceHelper.GetServiceJson(ServiceHelper.JsonType.Data, StatusConstants.Ok, DateList, "", true);
        //    else
        //    {
        //        dicto = new Dictionary<string, dynamic>();
        //        dicto.Add("Result", "Records not found");
        //        if (Convert.ToString(objProChat.ChatOn) == "1/1/1900 12:00:00 AM")
        //            dicto.Add("Date", new UserRepository().Getdate());
        //    }
        //    return dicto;
        //}

        [HttpPost]
        [ActionName("Truncate")]
        public dynamic Truncate()
        {
            Dictionary<string, dynamic> dicto;
            var detail = new UserRepository().Truncate();

            if (detail)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Truncated data Successfully");
            }
            else
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Truncate fail");
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("SearchUserByName")]
        public dynamic SearchUserByName(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var DateList = new UserRepository().GetUserBySerachName(User);

            if (DateList.Count > 0)
                dicto.Add("Result", DateList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("AddAsFriend")]
        public dynamic AddAsFriend(Pro_UserContact User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var Userid = Convert.ToInt32(new UserContactRepository().AddAsFriend(User));
            if (Userid > 0)
            {
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("AuthenticateUserForRestore")]
        public dynamic AuthenticateUserForRestore(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto;
            var detail = new UserRepository().RestoreUser(User);

            if (detail == -1)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "ContactNo does not exists");
            }
            else if (detail == -2)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Email does not exists");
            }
            else if (detail == 0)
            {
                dicto = new Dictionary<string, dynamic>();
                dicto.Add("Result", "Email and contact does not exists");
            }
            else
            {
                Random rnd = new Random();
                string code = rnd.Next(1000, 10000).ToString();
                if (code.Length == 3)
                    code = code + "0";
                else if (code.Length == 2)
                    code = code + "00";
                dicto = new Dictionary<string, dynamic>();


                //-------------------Send Email with varfication code--------------
                bool EmailStatus = EmailHelper.SendEmailForVarificationCode(User.EmailId, code, User.ContactNo);
                if (EmailStatus == true)
                {
                    dicto.Add("code", code);
                   // dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("RestoreUser")]
        public dynamic RestoreUser(Pro_UserMaster User)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserId = new UserRepository().RestoreUser(User);
            if (UserId > 0)
            {
                var UserProfile = new UserRepository().GetUserProfile(UserId);
                var FriendList = new UserContactRepository().GetContactList(UserId);
                if (UserProfile.UserId > 0)
                    dicto.Add("UserDetail", UserProfile);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
                //dicto.Add("RegistrationDate", new UserRepository().Getdate());

                if(FriendList.Count > 0)
                    dicto.Add("FriendList", FriendList);
                else
                    dicto.Add("Status", Convert.ToBoolean(0));

                return dicto;
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("checkForContact")]
        public dynamic checkForContact(Pro_UserMaster user)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var UserDetails = new ContactDetailsRepository().checkForContact(user.UserId, user.ContactNo);
            if (UserDetails.UserId > 0)
               dicto.Add("Result",UserDetails);
            else
                dicto.Add("Status", "0");
            return dicto;
        }

        [HttpPost]
        [ActionName("CustomPrivacySetting")]
        public dynamic CustomPrivacySetting(Pro_PrivacySetting user)
        {
            string UserSetting = string.Empty;
            string GroupSetting = string.Empty;
            int i = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();

            Pro_UserPrivacySetting objuser = new Pro_UserPrivacySetting();
            objuser.UserId = user.UserId;
            objuser.PrivacySetting = 2;
            var UserDetail = new UserRepository().UpdatePrivacySetting(objuser);
            if (UserDetail > 0)
            {
                UserSetting = Convert.ToString(user.UserSettingArray);
                GroupSetting = Convert.ToString(user.GroupSettingArray);

                //---User Setting array------------
                JavaScriptSerializer jss = new JavaScriptSerializer();
                List<Pro_UserPrivacySetting_Api> UserSettingList = jss.Deserialize<List<Pro_UserPrivacySetting_Api>>(UserSetting);
                //---End--------------------------

                //---User Setting array------------
                JavaScriptSerializer jss1 = new JavaScriptSerializer();
                List<Pro_GroupPrivacySetting_Api> GroupSettingList = jss1.Deserialize<List<Pro_GroupPrivacySetting_Api>>(GroupSetting);
                //---End--------------------------

                string result = new PrivacySettingRepository().InsertPrivacySetting(UserSettingList, GroupSettingList, user.UserId);
                if (result == "1")
                {
                    dicto.Add("Status", Convert.ToBoolean(1));
                }
                else
                    dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }
        #endregion

        [HttpPost]
        [ActionName("UploadVideo")]
        public dynamic Upload(Pro_VideoMaster_Api video)
        {
            Dictionary<string, dynamic> dicto;
            // byte[] b = Encoding.ASCII.GetBytes(video.buffer);
            long offset = Convert.ToInt64(video.Offset);
            string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["upload_path"]);
            var IsSuccess = new Helpers.HelperFunctions().UploadFile(video.FileName, video.buffer, offset, path);

            dicto = new Dictionary<string, dynamic>();
            dicto.Add("Result", IsSuccess);
            dicto.Add("Message", (IsSuccess == true ? "Success" : "Failure"));

            return dicto;

        }

        [HttpPost]
        [ActionName("InsertChatWithImageOrVideo1")]
        public dynamic InsertChatWithImageOrVideo1(Pro_ChatHistoryMaster chat)
        {
            string msg = string.Empty;
            bool IsSuccess;
            int chatId = 0;
            Pro_ChatHistoryMaster objchat = new Pro_ChatHistoryMaster();
            Pro_ChatDateDetail Chat = new Pro_ChatDateDetail();
            Pro_GroupChatDateDetail ChatDetail = new Pro_GroupChatDateDetail();
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            long offset = Convert.ToInt64(chat.Offset);
            string path = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["UploadChatImageVideo"]);

            if (chat.Upload == "Image")
                chat.ImagePath = chat.FileName;
            else
                chat.VideoPath = chat.FileName;
            if (chat.IsUploadingEnd == true)
            {
                new Helpers.HelperFunctions().UploadFile(chat.FileName, chat.buffer, offset, path);
                IsSuccess = false;
            }
            else
            {
                IsSuccess = new Helpers.HelperFunctions().UploadFile(chat.FileName, chat.buffer, offset, path);
                dicto.Add("Success", IsSuccess);
            }

            if (IsSuccess == false)
            {
                //--------------Thumb image------------------------------------
                if (chat.Upload == "Image")
                    Helpers.HelperFunctions.SaveThumbImage(path + chat.FileName, 100, 100, "Thumb_");
                //--------------End Thumb image--------------------------------
                //--------------Insert Process----------------------------------
                if (chat.GroupId != 0)
                {
                    ChatDetail = new ChatHistoryRepository().InsertGroupChat(chat);
                    if (ChatDetail.Status == true)
                        dicto.Add("Result", ChatDetail);
                    else
                    {
                        if (File.Exists(path + "/" + chat.FileName))
                            DeleteImageVideo(path + "/" + chat.FileName);
                        if (chat.Upload == "Image")
                            DeleteImageVideo(path + "/" + "Thumb_" + chat.FileName);
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
                else
                {
                    Chat = new ChatHistoryRepository().SaveChat(chat);
                    //chatId = Convert.ToInt32(new ChatHistoryRepository().SaveChat(chathistory));
                    if (Chat.ServerID > 0)
                    {
                        dicto.Add("Result", Chat);
                        //dicto.Add("Status", Convert.ToBoolean(1));
                    }
                    else
                    {
                        if (File.Exists(path + "/" + chat.FileName))
                        {
                            DeleteImageVideo(path + "/" + chat.FileName);
                            if (chat.Upload == "Image")
                                DeleteImageVideo(path + "/" + "Thumb_" + chat.FileName);
                        }
                        dicto.Add("Status", Convert.ToBoolean(0));
                    }
                }
            }
            //--------------End Insert Process-------------
            return dicto;
        }

        //[HttpPost]
        //[ActionName("UploadVideo1")]
        //public string UploadVideo1(Pro_VideoMaster_Api1 video)
        //{
        //    //Dictionary<string, dynamic> dicto;
        //    string FilePath=video.File;
        //    int Offset = 0; // starting offset.
        //    int ChunkSize = 65536;

        //    byte[] Buffer = new byte[ChunkSize];
        //    //opening the file for read.
        //    FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
        //    //creating the ServiceSoapClient which will allow to connect to the service.
        //    //WSservice.ServiceSoapClient soap_client = new WSservice.ServiceSoapClient();
        //    try
        //    {
        //        long FileSize = new FileInfo(FilePath).Length; // File size of file being uploaded.
        //        // reading the file.
        //        fs.Position = Offset;
        //        int BytesRead = 0;

        //        while (Offset != FileSize) // continue uploading the file chunks until offset = file size.
        //        {
        //            BytesRead = fs.Read(Buffer, 0, ChunkSize); // read the next chunk
        //            // (if it exists) into the buffer.
        //            // the while loop will terminate if there is nothing left to read
        //            // check if this is the last chunk and resize the buffer as needed
        //            // to avoid sending a mostly empty buffer
        //            // (could be 10Mb of 000000000000s in a large chunk)
        //            if (BytesRead != Buffer.Length)
        //            {
        //                ChunkSize = BytesRead;
        //                byte[] TrimmedBuffer = new byte[BytesRead];
        //                Array.Copy(Buffer, TrimmedBuffer, BytesRead);
        //                Buffer = TrimmedBuffer; // the trimmed buffer should become the new 'buffer'
        //            }
        //            // send this chunk to the server. it is sent as a byte[] parameter,
        //            // but the client and server have been configured to encode byte[] using MTOM.
        //            bool ChunkAppened = new VideoRepository().UploadFile(Path.GetFileName(FilePath), Buffer, Offset);
        //            if (!ChunkAppened)
        //            {
        //                break;
        //            }

        //            // Offset is only updated AFTER a successful send of the bytes.
        //            Offset += BytesRead; // save the offset position for resume
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //    }
        //    finally
        //    {
        //        fs.Close();
        //    }

        //    return "Success";

        //}

        [HttpPost]
        [ActionName("InsertComment")] //for on and of
        public dynamic InsertComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var CommentId = new CommentMasterRepository().SaveComment(Comment);

            if (Convert.ToInt32(CommentId) > 0)
            {
               // dicto.Add("CommentId", Convert.ToInt32(CommentId));
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("InsertLike")] //for on and of
        public dynamic InsertLike(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeId = new LikeMasterRepository().SaveLike(Like);

            if (Convert.ToInt32(LikeId) > 0)
            {
                //dicto.Add("LikeId", Convert.ToInt32(LikeId));
                dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("DeleteComment")] //for on and of
        public dynamic DeleteComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var CommentId = new CommentMasterRepository().DeleteComment(Comment.CommentId);

            if (Convert.ToInt32(CommentId) > 0)
            {
                dicto.Add("CommentId", Convert.ToInt32(CommentId));
                //dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("DeleteLike")] //for on and of
        public dynamic DeleteLike(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeId = new LikeMasterRepository().DeleteLike(Like.LikeId);

            if (Convert.ToInt32(LikeId) > 0)
            {
                dicto.Add("LikeId", Convert.ToInt32(LikeId));
                //dicto.Add("Status", Convert.ToBoolean(1));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }


        [HttpPost]
        [ActionName("GetComment")] //for on and of
        public dynamic GetComment(Pro_CommentMaster Comment)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string,dynamic>();
            var CommentList = new CommentMasterRepository().GetComment(Comment);

            if (CommentList.Count > 0)
                dicto.Add("Result", CommentList);
            else
                dicto.Add("Status", Convert.ToBoolean(0));

            return dicto;
        }

        [HttpPost]
        [ActionName("GetLikeCount")] //for on and of
        public dynamic GetLikeCount(Pro_LikeMaster Like)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var LikeCount = new LikeMasterRepository().GetLikeCount(Like);

            if (LikeCount > 0)
                dicto.Add("LikeCount", LikeCount);
            else
                dicto.Add("Status", Convert.ToBoolean(0));
            return dicto;
        }

        [HttpPost]
        [ActionName("GetRecentMsg")]
        public dynamic GetRecentMsg(Pro_ChatHistoryMaster Chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>(); ;
            List<Pro_FriendScreen_Api> chats = new ChatHistoryRepository().GetRecentMsg(Chat);
            if (chats.Count > 0)
            {
                dicto.Add("Result", chats);
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        //-------Add by Nirmal 7-01-2013-------
        [HttpPost]
        [ActionName("GetHighlightedContent")] //for send total like count and other information
        public dynamic GetLikeCount(Pro_LikesMaster objlikes)
        {
            const int pageSize = 10;
            int count = 0;
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var TotalLikecount = new LikeMasterRepository().GetAllLikesCount(objlikes.RecordIndex, objlikes.ContentType);
            if (TotalLikecount.Count > 0)
            {
                dicto.Add("Result", TotalLikecount);
                if (TotalLikecount.Count < pageSize || ((objlikes.RecordIndex + pageSize) == count))
                {
                    dicto.Add("Count", TotalLikecount.Count);
                    dicto.Add("Next", false);
                }
                else
                {
                    dicto.Add("Count", TotalLikecount.Count);
                    dicto.Add("Next", true);
                }
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        [HttpPost]
        [ActionName("GetHighlightedComments")]
        public dynamic GetComments(Pro_CommentsMaster objcomments)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var TotalComments = new LikeMasterRepository().GetAllComments(objcomments.ContentId, objcomments.ContentType);
            if (TotalComments.Count > 0)
            {
                dicto.Add("Result", TotalComments);
                dicto.Add("Count", TotalComments.Count);
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }

        //------------End-----------------

        [HttpPost]
        [ActionName("UpdateTypingStatus")]
        public dynamic UpdateTypingStatus(Pro_ChatHistoryMaster chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var Res = new ChatHistoryRepository().UpdateTypingStatus(chat);
            if (Convert.ToInt32(Res) > 0)
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }
    }
}
        [HttpPost]
        [ActionName("UpdateTypingStatus")]
        public dynamic UpdateTypingStatus(Pro_ChatHistoryMaster chat)
        {
            Dictionary<string, dynamic> dicto = new Dictionary<string, dynamic>();
            var Res = new ChatHistoryRepository().UpdateTypingStatus(chat);
            if (Convert.ToInt32(Res) > 0)
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            else
            {
                dicto.Add("Status", Convert.ToBoolean(0));
            }
            return dicto;
        }
    }
}