using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using RestSharp;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using WK_KLI_LAPS_Service.Controllers.WorkArea;
using Newtonsoft.Json.Linq;
using WK_KLI_LAPS_Service.App_Data;
using System.Data;
using WK_KLI_LAPS_Service.Models.Configuration;

namespace WK_KLI_LAPS_Service.Controllers.Common.Emailreader
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmailReaderApiController : ControllerBase
    {
        //static string from_address1 = System.Configuration.ConfigurationSettings.AppSettings["From_Address"].ToString();

        static string from_address = Startup.Configuration.GetValue<string>("Emailreader:From_Address");
        static string subject = Startup.Configuration.GetValue<string>("Emailreader:Subject");
        static string Top = Startup.Configuration.GetValue<string>("Emailreader:Top");
        static string usersmailid = Startup.Configuration.GetValue<string>("Emailreader:user_Address");
        string mailfoldename = Startup.Configuration.GetValue<string>("Emailreader:mailfoldername");
        static string chennaifolder = Startup.Configuration.GetValue<string>("Emailreader:CHE");
        static string pondyfolder = Startup.Configuration.GetValue<string>("Emailreader:PDY");
        static string chennai = Startup.Configuration.GetValue<string>("Emailreader:chennai");
        static string pondy = Startup.Configuration.GetValue<string>("Emailreader:pondicherry");
        static string Completed = Startup.Configuration.GetValue<string>("Emailreader:completefoldername");
        static string toptierfoldername = Startup.Configuration.GetValue<string>("Emailreader:toptierfoldername");
        static string categorycolorcode = Startup.Configuration.GetValue<string>("Emailreader:categorycolorcode");
        static string Clientid = Startup.Configuration.GetValue<string>("Emailreader:Clientid");
        static string Tenantid = Startup.Configuration.GetValue<string>("Emailreader:Tenantid");
        static string Secretid = Startup.Configuration.GetValue<string>("Emailreader:Secretid");

        WorkAreaService oWorkAreaService = new WorkAreaService();
        CommonRepository oCommonRepository = new CommonRepository();

        [Authorize]
        [HttpPost("movemessage")]
        public IActionResult movemessage()
        {
            var _list = new List<string>();
            try
            {
                if (Request.Form != null)
                {
                    string model = Request.Form["model"].ToString();
                    var jsonArray = JArray.Parse(model);
                    string lotid = string.Empty;
                    string mailid = string.Empty;
                    string option = string.Empty;
                    string username = string.Empty;
                    string Previousstage_username = string.Empty;
                    long tranid = 0;
                    long userid = 0;
                    string res = string.Empty;
                    string res_par = string.Empty;
                    foreach (var j in jsonArray)
                    {
                        lotid = j["lotid"].ToString();
                        mailid = j["mailid"].ToString();
                        option = j["option"].ToString();
                        tranid = Convert.ToInt64(j["tranid"]);
                        userid = Convert.ToInt64(j["userid"]);
                        if (!string.IsNullOrEmpty(mailid))
                        {
                            var input8 = new { userid_p = userid };
                            var jsonstr8 = JsonConvert.SerializeObject(input8);
                            string dt3 = JsonConvert.SerializeObject(CommonRepository.ExecuteSP_ReturnList2("spusermasterselect", jsonstr8, "getbyuserid"));
                            dt3 = dt3.Replace("\\\"", "\"");
                            DataTable userdata = oCommonRepository.JsonStringToDataTable(dt3);
                            if (userdata.Rows.Count > 0)
                            {
                                username = userdata.Rows[0]["username"].ToString();
                            }
                            if (tranid != 0)
                            {
                                var input = new { tranid = tranid };
                                var jsonstr = JsonConvert.SerializeObject(input);
                                string dt4 = JsonConvert.SerializeObject(CommonRepository.ExecuteSP_ReturnList2("spgetprevoiusstagedetails", jsonstr, null));
                                dt4 = dt4.Replace("\\\"", "\"");
                                DataTable Previousstage_userdata = oCommonRepository.JsonStringToDataTable(dt4);
                                if (Previousstage_userdata.Rows.Count > 0)
                                {
                                    Previousstage_username = Previousstage_userdata.Rows[0]["username"].ToString();
                                }
                            }

                            string parentid = string.Empty;
                            string main = string.Empty;
                            List<folderdetails> MainFolder = new List<folderdetails>();
                            List<folderdetails> AllSubFoldersName = new List<folderdetails>();
                            List<folderdetails> AllcategorySubFoldersName = new List<folderdetails>();
                            List<folderdetails> selectedcategory = new List<folderdetails>();
                            List<categoriesdetails> AllCategories = new List<categoriesdetails>();
                            List<categoriesdetails> Categoriesexist = new List<categoriesdetails>();
                            //string categoryfoldername = string.Empty;
                            /*Get category and check*/
                            var category = GetAllCategory();
                            var category_list = category.Item1.value;
                            if (category_list.Count > 0)
                            {
                                for (int i = 0; i < category_list.Count; i++)
                                {
                                    AllCategories.Add(new categoriesdetails { displayname = category_list[i].displayName, color = category_list[i].color, id = category_list[i].id, });
                                }
                            }
                            Categoriesexist = AllCategories.Where(x => x.displayname == option).ToList();
                            if (Categoriesexist.Count == 0)
                            {
                                int colorcode = getrandom();
                                var color = categorycolorcode + colorcode;
                                var createusercategory = Postcategory(option, color);
                            }
                            /*Main folder get*/
                            var Mainfolders = GetFolders();
                            var Mainfolders_lst = Mainfolders.Item1.value;
                            if (Mainfolders_lst.Count > 0)
                            {
                                for (int i = 0; i < Mainfolders_lst.Count; i++)
                                {
                                    if (Mainfolders_lst[i].displayName.ToLower() == mailfoldename)
                                    {
                                        MainFolder.Add(new folderdetails { displayname = Mainfolders_lst[i].displayName, id = Mainfolders_lst[i].id, parentFolderId = Mainfolders_lst[i].parentFolderId });
                                        break;
                                    }

                                }
                            }
                            /*Sub folder get*/
                            var subfolders = GetChildFolders();
                            var subfolders_lst = subfolders.Item1.value;
                            if (subfolders_lst.Count > 0)
                            {
                                for (int i = 0; i < subfolders_lst.Count; i++)
                                {
                                    if (subfolders_lst[i].displayName.ToLower().TrimEnd() == Completed)
                                    {
                                        AllSubFoldersName.Add(new folderdetails { displayname = subfolders_lst[i].displayName, id = subfolders_lst[i].id, parentFolderId = subfolders_lst[i].parentFolderId });
                                        break;
                                    }
                                }
                                var userfolders = GetChildChildFolders(AllSubFoldersName[0].id);
                                var userfolder_lst = userfolders.Item1.value;
                                for (int k = 0; k < userfolder_lst.Count; k++)
                                {
                                    AllcategorySubFoldersName.Add(new folderdetails { displayname = userfolder_lst[k].displayName, id = userfolder_lst[k].id, parentFolderId = userfolder_lst[k].parentFolderId });
                                }
                                selectedcategory = AllcategorySubFoldersName.Where(x => x.displayname.Contains(option)).ToList();
                                if (selectedcategory.Count > 0)
                                {
                                    var getallmails = GetAllMessages();
                                    var getallmessages = getallmails.Item1.value;
                                    if (getallmessages != null)
                                    {
                                        if (getallmessages.Count > 0)
                                        {
                                            for (int i = 0; i < getallmessages.Count; i++)
                                            {
                                                if (getallmessages[i].id == mailid)
                                                {
                                                    main = getallmessages[i].parentFolderId;
                                                }
                                            }
                                        }

                                    }
                                    if (!string.IsNullOrEmpty(main))
                                    {
                                        parentid = selectedcategory[0].id;
                                        //move mail
                                        var movemail = MoveMessages(mailid, main, parentid);
                                        var movedetails = movemail.Item1.value;
                                        string user = string.Empty;
                                        if (string.IsNullOrEmpty(Previousstage_username))
                                        {
                                            user = username;
                                        }
                                        else
                                        {
                                            user = Previousstage_username;
                                        }
                                        var updatemsgwithcategory = updatemessage(parentid, movemail.Item1.id, option, user);
                                        lotmasterModel olotmaster = new lotmasterModel();
                                        olotmaster.lotid = Convert.ToInt32(lotid);
                                        olotmaster.uniquemailid = movemail.Item1.id;
                                        olotmaster.parentmailid = parentid;
                                        olotmaster.createdby = Convert.ToInt32(userid);
                                        olotmaster.option = "updatelot_mailid";
                                        string inputstr = JsonConvert.SerializeObject(olotmaster);
                                        var retval1 = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, olotmaster.option);
                                        res = movemail.Item1.id;
                                        res_par = parentid;
                                        _list.Add(res);
                                        _list.Add(res_par);
                                    }
                                }
                            }
                        }
                        else
                        {
                            _list.Add("Mailid not exist");
                        }
                    }

                    return Ok(_list);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                _list.Add("{\"result\":" + ex.ToString() + "}");
                return Ok(_list);
            }
        }

        [Authorize]
        [HttpPost("movemailtoassignuserfold")]
        public IActionResult movemailtoassignuserfold()
        {
            var _list = new List<string>();
            try
            {
                if (Request.Form != null)
                {
                    string model = Request.Form["model"].ToString();
                    var jsonArray = JArray.Parse(model);
                    string lotid = string.Empty;
                    string mailid = string.Empty;
                    string sflag = string.Empty;
                    string alreadyassignuser = string.Empty;
                    string lotstatus = string.Empty;
                    string parentmailid = string.Empty;
                    long alreadyassignuserid = 0;
                    long userid = 0;
                    long stageorder = 0;
                    string foldername = string.Empty; //user folder name
                    string userlocation = string.Empty;//user location

                    foreach (var j in jsonArray)
                    {
                        lotid = j["lotid"].ToString();
                        mailid = j["uniquemailid"].ToString();
                        alreadyassignuser = j["assignedUser"].ToString();
                        lotstatus = j["lotstatus"].ToString();
                        parentmailid = j["parentmailid"].ToString();
                        userid = Convert.ToInt64(j["selectUser"]);
                        stageorder = Convert.ToInt64(j["stageorder"]);
                        if (j["sflag"] == null)
                        {
                            alreadyassignuserid = Convert.ToInt64(j["assigned_user"]);
                            if (alreadyassignuserid == 0)
                            {
                                sflag = "1";
                            }
                            else if (alreadyassignuserid == userid)
                            {
                                sflag = "3";
                            }
                            else if (alreadyassignuserid != userid)
                            {
                                sflag = "1";
                            }
                        }
                        else
                        {
                            sflag = j["sflag"].ToString();
                        }

                        var input8 = new { userid_p = userid };
                        var jsonstr8 = JsonConvert.SerializeObject(input8);
                        string dt3 = JsonConvert.SerializeObject(CommonRepository.ExecuteSP_ReturnList2("spusermasterselect", jsonstr8, "getbyuserid"));
                        dt3 = dt3.Replace("\\\"", "\"");
                        DataTable userdata = oCommonRepository.JsonStringToDataTable(dt3);
                        if (userdata.Rows.Count > 0)
                        {
                            foldername = userdata.Rows[0]["username"].ToString();
                            string user_location = userdata.Rows[0]["location"].ToString();
                            if (user_location.ToLower().Contains(chennai)) userlocation = chennaifolder;
                            if (user_location.ToLower().Contains(pondy)) userlocation = pondyfolder;
                            if (string.IsNullOrEmpty(userlocation))
                            {
                                userlocation = pondyfolder;

                            }
                        }

                        if (!string.IsNullOrEmpty(mailid))
                        {
                            //***move mail to assigned user folder****//
                            List<folderdetails> AllSubFoldersName = new List<folderdetails>();
                            List<folderdetails> AlluserSubFoldersName = new List<folderdetails>();
                            List<folderdetails> useralredyexist = new List<folderdetails>();
                            List<folderdetails> locationfolder = new List<folderdetails>();
                            List<folderdetails> MainFolder = new List<folderdetails>();
                            List<folderdetails> useralredyassigned = new List<folderdetails>();
                            List<categoriesdetails> AllCategories = new List<categoriesdetails>();
                            List<categoriesdetails> userCategoriesexist = new List<categoriesdetails>();
                            var issubfolderexist = false;
                            /*start*/
                            /*Get category and check*/
                            var category = GetAllCategory();
                            var category_list = category.Item1.value;
                            if (category_list.Count > 0)
                            {
                                for (int i = 0; i < category_list.Count; i++)
                                {
                                    AllCategories.Add(new categoriesdetails { displayname = category_list[i].displayName, color = category_list[i].color, id = category_list[i].id, });
                                }
                            }
                            userCategoriesexist = AllCategories.Where(x => x.displayname == foldername).ToList();
                            if (userCategoriesexist.Count == 0)
                            {
                                int colorcode = getrandom();
                                var color = categorycolorcode + colorcode;
                                var createusercategory = Postcategory(foldername, color);
                            }

                            /*Main folder get*/
                            var Mainfolders = GetFolders();
                            var Mainfolders_lst = Mainfolders.Item1.value;
                            if (Mainfolders_lst.Count > 0)
                            {
                                for (int i = 0; i < Mainfolders_lst.Count; i++)
                                {
                                    if (Mainfolders_lst[i].displayName.ToLower() == mailfoldename)
                                    {
                                        MainFolder.Add(new folderdetails { displayname = Mainfolders_lst[i].displayName, id = Mainfolders_lst[i].id, parentFolderId = Mainfolders_lst[i].parentFolderId });
                                        break;
                                    }

                                }
                            }

                            if (sflag == "1")
                            {
                                /*Sub folder get*/

                                var subfolders = GetChildFolders();
                                var subfolders_lst = subfolders.Item1.value;
                                if (subfolders_lst.Count > 0)
                                {
                                    for (int i = 0; i < subfolders_lst.Count; i++)
                                    {
                                        if (subfolders_lst[i].displayName == userlocation)
                                        {
                                            issubfolderexist = true;
                                            AllSubFoldersName.Add(new folderdetails { displayname = subfolders_lst[i].displayName, id = subfolders_lst[i].id, parentFolderId = subfolders_lst[i].parentFolderId });
                                            break;
                                        }

                                    }
                                    if (!issubfolderexist)
                                    {
                                        //location folder create
                                        var createfolder = PostChildFolders(userlocation, MainFolder[0].id);

                                        var createfolderdetails = createfolder.Item1.id;
                                        if (createfolderdetails != null)
                                        {
                                            AllSubFoldersName.Add(new folderdetails { displayname = userlocation, id = createfolder.Item1.id, parentFolderId = MainFolder[0].id });

                                        }

                                    }
                                    if (AllSubFoldersName[0].id != null)
                                    {
                                        var userfolders = GetChildChildFolders(AllSubFoldersName[0].id);
                                        var userfolder_lst = userfolders.Item1.value;
                                        for (int k = 0; k < userfolder_lst.Count; k++)
                                        {
                                            AlluserSubFoldersName.Add(new folderdetails { displayname = userfolder_lst[k].displayName, id = userfolder_lst[k].id, parentFolderId = userfolder_lst[k].parentFolderId });
                                        }
                                    }
                                    //check user folder exist
                                    useralredyexist = AlluserSubFoldersName.Where(x => x.displayname.Equals(foldername)).ToList();
                                    if (!string.IsNullOrEmpty(alreadyassignuser))
                                    {
                                        useralredyassigned = AlluserSubFoldersName.Where(x => x.displayname.Equals(alreadyassignuser)).ToList();
                                    }
                                    locationfolder = AllSubFoldersName.Where(x => x.displayname.Equals(userlocation)).ToList();

                                    if (useralredyexist.Count == 0)
                                    {
                                        //user folder create
                                        var createfolder = PostChildFolders(foldername, locationfolder[0].id);
                                        var createfolderdetails = createfolder.Item1.value;
                                        var parentid = ""; var main = "";
                                        if (string.IsNullOrEmpty(alreadyassignuser))
                                        {
                                            parentid = createfolder.Item1.id;
                                            if (stageorder == 1) main = toptierfoldername;
                                            if (stageorder == 2) main = parentmailid;
                                        }
                                        else
                                        {
                                            parentid = createfolder.Item1.id;
                                            if (stageorder == 1) main = useralredyassigned[0].id;
                                            if (stageorder == 2) main = parentmailid;
                                        }
                                        //move mail
                                        var movemail = MoveMessages(mailid, main, parentid);
                                        var movedetails = movemail.Item1.value;
                                        var updatemsgwithcategory = updatemessage(parentid, movemail.Item1.id, foldername);
                                        //need update maild in lot master
                                        lotmasterModel olotmaster = new lotmasterModel();
                                        olotmaster.lotid = Convert.ToInt32(lotid);
                                        olotmaster.uniquemailid = movemail.Item1.id;
                                        olotmaster.parentmailid = parentid;
                                        olotmaster.createdby = Convert.ToInt32(userid);
                                        olotmaster.option = "updatelot_mailid";
                                        string inputstr = JsonConvert.SerializeObject(olotmaster);
                                        var retval1 = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, olotmaster.option);
                                    }
                                    else
                                    {
                                        var parentid = ""; var main = "";
                                        if (string.IsNullOrEmpty(alreadyassignuser))
                                        {

                                            parentid = useralredyexist[0].id;

                                            if (stageorder == 1) main = toptierfoldername;
                                            if (stageorder == 2) main = parentmailid;
                                        }
                                        else
                                        {
                                            parentid = useralredyexist[0].id;
                                            if (stageorder == 1) main = useralredyassigned[0].id;
                                            if (stageorder == 2) main = parentmailid;
                                        }

                                        //move mail
                                        var movemail = MoveMessages(mailid, main, parentid);
                                        var movedetails = movemail.Item1.value;
                                        var updatemsgwithcategory = updatemessage(parentid, movemail.Item1.id, foldername);
                                        lotmasterModel olotmaster = new lotmasterModel();
                                        olotmaster.lotid = Convert.ToInt32(lotid);
                                        olotmaster.uniquemailid = movemail.Item1.id;
                                        olotmaster.parentmailid = parentid;
                                        olotmaster.createdby = Convert.ToInt32(userid);
                                        olotmaster.option = "updatelot_mailid";
                                        string inputstr = JsonConvert.SerializeObject(olotmaster);
                                        var retval1 = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, olotmaster.option);

                                    }

                                }
                                else
                                {
                                    //location folder create
                                    var createfolder = PostChildFolders(userlocation, MainFolder[0].id);
                                    var createfolderdetails = createfolder.Item1.id;

                                    if (createfolderdetails != null)
                                    {
                                        //user folder create
                                        createfolder = PostChildFolders(foldername, createfolderdetails);
                                        createfolderdetails = createfolder.Item1.id;
                                        //move mail
                                        var movemail = MoveMessages(mailid, toptierfoldername, createfolderdetails);
                                        var movedetails = movemail.Item1.value;
                                        var updatemsgwithcategory = updatemessage(createfolderdetails, movemail.Item1.id, foldername);
                                        //need update maild in lot master
                                        lotmasterModel olotmaster = new lotmasterModel();
                                        olotmaster.lotid = Convert.ToInt32(lotid);
                                        olotmaster.uniquemailid = movemail.Item1.id;
                                        olotmaster.parentmailid = createfolderdetails;
                                        olotmaster.createdby = Convert.ToInt32(userid);
                                        olotmaster.option = "updatelot_mailid";
                                        string inputstr = JsonConvert.SerializeObject(olotmaster);
                                        var retval1 = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, olotmaster.option);

                                    }
                                }
                            }
                            else if (sflag == "3")
                            {
                                var subfolders = GetChildFolders();
                                var subfolders_lst = subfolders.Item1.value;
                                if (subfolders_lst.Count > 0)
                                {
                                    for (int i = 0; i < subfolders_lst.Count; i++)
                                    {
                                        if (subfolders_lst[i].displayName == userlocation)
                                        {
                                            issubfolderexist = true;
                                            AllSubFoldersName.Add(new folderdetails { displayname = subfolders_lst[i].displayName, id = subfolders_lst[i].id, parentFolderId = subfolders_lst[i].parentFolderId });
                                            break;
                                        }

                                    }
                                    if (AllSubFoldersName[0].id != null)
                                    {
                                        var userfolders = GetChildChildFolders(AllSubFoldersName[0].id);
                                        var userfolder_lst = userfolders.Item1.value;
                                        for (int k = 0; k < userfolder_lst.Count; k++)
                                        {
                                            AlluserSubFoldersName.Add(new folderdetails { displayname = userfolder_lst[k].displayName, id = userfolder_lst[k].id, parentFolderId = userfolder_lst[k].parentFolderId });
                                        }
                                    }
                                    //check user folder exist
                                    useralredyexist = AlluserSubFoldersName.Where(x => x.displayname.Equals(foldername)).ToList();


                                    var main = useralredyexist[0].id;
                                    //move mail
                                    var movemail = MoveMessages(mailid, main, toptierfoldername);
                                    var movedetails = movemail.Item1.value;
                                    //remove category from mail
                                    var updatemsgwithcategory = updatemessage(toptierfoldername, movemail.Item1.id, foldername, null, 1);
                                    lotmasterModel olotmaster = new lotmasterModel();
                                    olotmaster.lotid = Convert.ToInt32(lotid);
                                    olotmaster.uniquemailid = movemail.Item1.id;
                                    olotmaster.parentmailid = toptierfoldername;
                                    olotmaster.createdby = Convert.ToInt32(userid);
                                    olotmaster.option = "updatelot_mailid";
                                    string inputstr = JsonConvert.SerializeObject(olotmaster);
                                    var retval1 = CommonRepository.ExecuteSP_ReturnList2("cc_createlotandtrans", inputstr, olotmaster.option);
                                }
                            }


                            _list.Add("done");

                        }
                        else
                        {
                            _list.Add("Mailid not exist");
                        }
                    }
                    return Ok(_list);
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                _list.Add("{\"result\":" + ex.ToString() + "}");
                return Ok(_list);
            }

        }
        [Authorize]
        [HttpPost("GetMailDetailsByID")]
        public object GetMailDetailsByID()
        {
            var _list = new List<string>();
            try
            {
                if (Request.Form != null)
                {
                    string model = Request.Form["model"].ToString();
                    var jsonArray = JArray.Parse(model);
                    string mailid = string.Empty;
                    string parentmailid = string.Empty;
                    messagedetails msgdata = new messagedetails();
                    foreach (var j in jsonArray)
                    {
                        mailid = j["mailid"].ToString();
                        parentmailid = j["parentid"].ToString();
                        var mails = GetMessages_ByID(mailid,parentmailid);
                        var messages = mails.Item1;
                        if(!string.IsNullOrEmpty(mails.Item1.id))msgdata.id = mails.Item1.id.ToString();
                        if (!string.IsNullOrEmpty(mails.Item1.subject)) msgdata.subject = mails.Item1.subject.ToString();
                        if (mails.Item1.body !=null) msgdata.body = mails.Item1.body.content.ToString();
                        if (mails.Item1.receivedDateTime != null) msgdata.rec_date = mails.Item1.receivedDateTime;
                        if (mails.Item1.from!= null) msgdata.from_email = mails.Item1.from.emailAddress.address.ToString();
                        //if (messages.Count > 0)
                        //{

                        //    for (int i = 0; i < messages.Count; i++)
                        //    {

                        //        msgdata.id = messages[i].id.ToString();
                        //        msgdata.subject = messages[i].subject.ToString();
                        //        msgdata.body = messages[i].body.content.ToString();
                        //        msgdata.rec_date = messages[i].receivedDateTime.ToString();
                        //            msgdata.from_email = messages[i].from.emailAddress.address.ToString();
                        //    }
                        //}
                    }

                        return msgdata;
                }
                else
                {
                        return null;
                }
                
            }
            catch (Exception ex)
            {
                _list.Add("{\"result\":" + ex.ToString() + "}");
                return Ok(_list);
            }
        }

        #region oldcode
        //[Authorize]
        //[HttpPost("movemessage")]
        //public IActionResult movemessage()
        //{
        //    var _list = new List<string>();
        //    try
        //    {
        //        if (Request.Form != null)
        //        {
        //            string model = Request.Form["model"].ToString();
        //            var jsonArray = JArray.Parse(model);
        //            string jobid = string.Empty;
        //            string jobworkflowid = string.Empty;
        //            string lotid = string.Empty;
        //            string mailid = string.Empty;
        //            string nextstage = string.Empty;
        //            string option = string.Empty;
        //            string foldername = string.Empty;

        //            foreach (var j in jsonArray)
        //            {
        //                jobid = j["jobid"].ToString();
        //                jobworkflowid = j["jobworkflowid"].ToString();
        //                lotid = j["lotid"].ToString();
        //                mailid = j["mailid"].ToString();
        //                nextstage = j["nextstage"].ToString();
        //                option = j["option"].ToString();
        //                if (!string.IsNullOrEmpty(mailid))
        //                {
        //                    string last_stage_workflowid = string.Empty;
        //                    var checknextasfinal = oWorkAreaService.checknextisfinal(Convert.ToInt64(jobid));
        //                    if (checknextasfinal != null)
        //                    {
        //                        var i1 = JsonConvert.DeserializeObject<object>(checknextasfinal.ToString());
        //                        JArray a1 = JArray.Parse(i1.ToString());
        //                        JObject obj1 = JObject.Parse(a1[0].ToString());
        //                        last_stage_workflowid = obj1["last_stage_workflowid"].ToString();
        //                    }
        //                    if (nextstage == last_stage_workflowid)
        //                    {
        //                        //***move mail to complete folder****//
        //                        // check all lot complete
        //                        var isalllotcomplete = checkallLotComplete(jobid.ToString(), lotid);
        //                        if (isalllotcomplete == null)
        //                        {
        //                            //var mails = GetMessages();
        //                            //var messages = mails.Item1.value;
        //                            //if (messages.Count > 0)
        //                            //{
        //                            //    for (int i = 0; i < messages.Count; i++)
        //                            //    {
        //                            //        mailid = messages[i].id;
        //                            //    }
        //                            //}

        //                            // move msg to mail folder
        //                            List<folderdetails> AllFoldersName = new List<folderdetails>();
        //                            var folders = GetFolders();
        //                            var folder_lst = folders.Item1.value;
        //                            if (folder_lst.Count > 0)
        //                            {
        //                                for (var i = 0; i < folder_lst.Count; i++)
        //                                {
        //                                    AllFoldersName.Add(new folderdetails
        //                                    {
        //                                        displayname = folder_lst[i].displayName,
        //                                        id = folder_lst[i].id
        //                                    });
        //                                }
        //                                //decide which folder to move mail
        //                                if (option == "checkout")
        //                                {
        //                                    foldername = Startup.Configuration.GetValue<string>("Emailreader:completefoldername");
        //                                }
        //                                else if (option == "duplicate")
        //                                {
        //                                    foldername = Startup.Configuration.GetValue<string>("Emailreader:duplicatefoldername");
        //                                }
        //                                else if (option == "norecord")
        //                                {
        //                                    foldername = Startup.Configuration.GetValue<string>("Emailreader:norecordfoldername");
        //                                }
        //                                if (!AllFoldersName.Exists(f => f.displayname.Equals(foldername)))
        //                                {
        //                                    //create
        //                                    var createfolder = PostFolders(foldername);
        //                                    var createfolderdetails = createfolder.Item1.id;
        //                                    if (createfolderdetails != null)
        //                                    {
        //                                        //move mails
        //                                        var movemail = MoveMessages(mailid.ToString(), mailfoldename, createfolderdetails.ToString());

        //                                        var movedetails = movemail.Item1.value;
        //                                    }
        //                                }
        //                                else
        //                                {
        //                                    //move
        //                                    var folderid = AllFoldersName.Where(f => f.displayname.Equals(foldername)).FirstOrDefault();
        //                                    if (folderid.id != "")
        //                                    {

        //                                        var movemail = MoveMessages(mailid, mailfoldename, folderid.id);
        //                                        var movedetails = movemail.Item1.value;
        //                                    }
        //                                }
        //                            }
        //                        }
        //                        var call_archievedetails = call_archive(Convert.ToInt64(jobid), Convert.ToInt64(lotid));
        //                        //var call_archievedetails = null;
        //                        string result = string.Empty;
        //                        if (call_archievedetails != null)
        //                        {
        //                            var i1 = JsonConvert.DeserializeObject<object>(call_archievedetails.ToString());
        //                            JArray a1 = JArray.Parse(i1.ToString());
        //                            JObject obj1 = JObject.Parse(a1[0].ToString());
        //                            result = obj1["result"].ToString();
        //                        }
        //                        if (result != "Done")
        //                        {
        //                            _list.Add("Error in archieve details");
        //                        }
        //                        _list.Add("done");
        //                    }
        //                }
        //                else
        //                {
        //                    _list.Add("Mailid not exist");
        //                }
        //            }
        //            return Ok(_list);
        //        }
        //        else
        //        {
        //            return null;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        _list.Add("{\"result\":" + ex.ToString() + "}");
        //        return Ok(_list);
        //    }
        //}
        //[Authorize]
        //[HttpPost("movemessage")]
        //public IActionResult movemessage()
        //{
        //    var _list = "";
        //        try
        //    {
        //        if (Request.Form != null)
        //        {
        //            var jobid = Request.Form["jobid"];
        //            var jobworkflowid = Request.Form["jobworkflowid"];
        //            var lotid = Request.Form["lotid"];
        //            var mailid = Request.Form["mailid"];
        //            var nextstage = Request.Form["nextstage"];
        //            var type = Request.Form["nextstage"];

        //            string last_stage_workflowid = string.Empty;
        //            var checknextasfinal = oWorkAreaService.checknextisfinal(Convert.ToInt64(jobid));
        //            if (checknextasfinal != null)
        //            {
        //                var i1 = JsonConvert.DeserializeObject<object>(checknextasfinal.ToString());
        //                JArray a1 = JArray.Parse(i1.ToString());
        //                JObject obj1 = JObject.Parse(a1[0].ToString());
        //                last_stage_workflowid = obj1["last_stage_workflowid"].ToString();
        //            }
        //            if (nextstage == last_stage_workflowid)
        //            {
        //                //***move mail to complete folder****//
        //               // check all lot complete
        //                var isalllotcomplete = checkallLotComplete(jobid.ToString(), lotid);
        //                if (isalllotcomplete == null)
        //                {
        //                    //var mails = GetMessages();
        //                    //var messages = mails.Item1.value;
        //                    //if (messages.Count > 0)
        //                    //{
        //                    //    for (int i = 0; i < messages.Count; i++)
        //                    //    {
        //                    //        var msgid = messages[i].id;
        //                    //    }
        //                    //}

        //                   // move msg to mail folder
        //                                        List<folderdetails> AllFoldersName = new List<folderdetails>();
        //                    var folders =GetFolders();
        //                    var folder_lst = folders.Item1.value;
        //                    if (folder_lst.Count > 0)
        //                    {
        //                        for (var i = 0; i < folder_lst.Count; i++)
        //                        {
        //                            AllFoldersName.Add(new folderdetails
        //                            {
        //                                displayname = folder_lst[i].displayName,
        //                                id = folder_lst[i].id
        //                            });
        //                        }
        //                        string foldername = Startup.Configuration.GetValue<string>("Emailreader:completefoldername");
        //                        if (!AllFoldersName.Exists(f => f.displayname.Equals(foldername)))
        //                        {
        //                            //create
        //                            var createfolder = PostFolders(foldername);
        //                            var createfolderdetails = createfolder.Item1.id;
        //                            if (createfolderdetails != null)
        //                            {
        //                                //move mails
        //                                var movemail = MoveMessages(mailid.ToString(), createfolderdetails.ToString());

        //                                var movedetails = movemail.Item1.value;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            //move
        //                            var folderid = AllFoldersName.Where(f => f.displayname.Equals(foldername)).FirstOrDefault();
        //                            if (folderid.id != "")
        //                            {
        //                                // mailfoldename = AllFoldersName.Where(f => f.displayname.ToLower().Equals(mailfoldename)).FirstOrDefault().id;
        //                                var movemail = MoveMessages(mailid, folderid.id);
        //                                var movedetails = movemail.Item1.value;
        //                            }
        //                        }
        //                    }
        //                }
        //            }
        //            int r = 1;
        //            if (r == 0)
        //            {
        //                var call_archievedetails = call_archive(Convert.ToInt64(jobid), Convert.ToInt64(lotid));
        //                //var call_archievedetails = null;
        //                string result = string.Empty;
        //                if (call_archievedetails != null)
        //                {
        //                    var i1 = JsonConvert.DeserializeObject<object>(call_archievedetails.ToString());
        //                    JArray a1 = JArray.Parse(i1.ToString());
        //                    JObject obj1 = JObject.Parse(a1[0].ToString());
        //                    result = obj1["result"].ToString();
        //                }
        //                if (result != "Done")
        //                {
        //                     _list = "error";
        //                }

        //            }
        //            _list = "done";
        //        }

        //        return Ok(_list);
        //    }
        //    catch (Exception ex)
        //    {
        //         _list = ex.ToString();
        //        return Ok(_list);
        //    } 
        //}
        #endregion

        public object checkallLotComplete(string jobid, string lotid)
        {
            var data = new { jobid = jobid, lotid = lotid };
            var jsonstr = JsonConvert.SerializeObject(data);

            return oCommonRepository.ExecuteSP_ReturnList1("cc_checkalllotcomplete", jsonstr);

        }
        public object call_archive(long jobid, long lotid)
        {
            var data = new { jobid = jobid, lotid = lotid, p_option = "C" };
            var jsonstr = JsonConvert.SerializeObject(data);

            return oCommonRepository.ExecuteSP_ReturnList1("cc_getarchievedetails", jsonstr);

        }
        public int getrandom()
        {
            int r = 0;
            Random rnd = new Random();
            for (int j = 0; j < 1; j++)
            {
                r = rnd.Next(0, 25);// returns random integers >= 0 and < 25
            }
            return r;
        }
        private Tuple<Mail, string> Postcategory(string categoryname, string colour)
        {
            string token = getToken();
            Mail messages = new Mail();
            /**create mail folder**/
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/outlook/masterCategories");
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            var body = @"{""displayName"": """ + categoryname + "\",\"color\":\"" + colour + "\"}";
            //preset7
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            RestResponse response = (RestResponse)client.Execute(request, Method.POST);
            if (response.StatusCode.ToString().Contains("Created"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }

            return new Tuple<Mail, string>(messages, token);
        }
        private Tuple<Mail, string> updatemessage(string parentid, string msgid, string categoryname, string categoryname2 = null, int isremove = 0)
        {
            string token = getToken();
            Mail messages = new Mail();
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders/" + parentid + "/messages/" + msgid);
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            //var body = @" {""categories"": [""" + categoryname + "\"]}";
            var body = "";
            if (isremove == 0)
            {
                if (string.IsNullOrEmpty(categoryname2))
                {
                    body = @" {""categories"": [""" + categoryname + "\"]}";
                }
                else
                {
                    body = @" {""categories"": [""" + categoryname + "\",\"" + categoryname2 + "\"]}";
                }
            }
            else
            {
                body = @" {""categories"": []}";//remove category
            }
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            RestResponse response = (RestResponse)client.Execute(request, Method.PATCH);
            if (response.StatusCode.ToString().Contains("OK"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }

            return new Tuple<Mail, string>(messages, token);
        }
        private Tuple<Mail, string> GetAllCategory()
        {
            string token = getToken();
            Mail messages = new Mail();
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/outlook/masterCategories?");
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            RestResponse response = (RestResponse)client.Execute(request, Method.GET);
            if (response.StatusCode.ToString().Contains("OK"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }
            return new Tuple<Mail, string>(messages, token);
        }
        private Tuple<Mail, string> GetAllMessages()
        {
            string token = getToken();
            Mail messages = new Mail();
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/messages?$top =" + Top);
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            RestResponse response = (RestResponse)client.Execute(request, Method.GET);
            if (response.StatusCode.ToString().Contains("OK"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }
            return new Tuple<Mail, string>(messages, token);
        }
        public void GetAttchments()
        {
            string msgid = string.Empty;
            List<string> AllMessageIDs = new List<string>();
            List<folderdetails> AllFoldersName = new List<folderdetails>();

            var folders = GetFolders();
            var folder_lst = folders.Item1.value;
            if (folder_lst.Count > 0)
            {
                for (var i = 0; i < folder_lst.Count; i++)
                {
                    AllFoldersName.Add(new folderdetails
                    {
                        displayname = folder_lst[i].displayName,
                        id = folder_lst[i].id
                    });
                }
            }
            var mails = GetMessages();
            var messages = mails.Item1.value;
            if (messages.Count > 0)
            {

                for (int i = 0; i < messages.Count; i++)
                {
                    msgid = messages[i].id;
                    // var movemail = MoveMessages(msgid, "AQMkAGNlOWI1ZWNmLThhMGUtNGE5OC05ZTE0LWE4YWU1YzU5NDYxYgAuAAADfaNCEPCMTkK6g5BwphPFSAEAoWU_HrrEnUqJJBZRSSyZiAAAAgEMAAAA");
                    Console.WriteLine("Id: " + messages[i].id);
                    Console.WriteLine("Subject: " + messages[i].subject);
                    Console.WriteLine("ReceivedTime: " + messages[i].receivedDateTime);
                    Console.WriteLine("From: " + messages[i].from.emailAddress.address);
                    Console.WriteLine("body: " + messages[i].body.content);
                    Console.WriteLine("---------------------------------------");
                }
            }
        }
        public Tuple<Mail, string> MoveMessages(string msgid, string mailfol, string folderid)
        {
            string token = getToken();
            Mail messages = new Mail();
            /**move mail to another folder**/
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders/" + mailfol + "/messages/" + msgid + "/move?");
            //  var client = new RestClient("https://graph.microsoft.com/v1.0/users/satya.dani@luminad.com/mailFolders/inbox/messages/AQMkAGNlOWI1ZWNmLThhMGUtNGE5OC05ZTE0LWE4YWU1YzU5NDYxYgBGAAADfaNCEPCMTkK6g5BwphPFSAcAoWU_HrrEnUqJJBZRSSyZiAAAAgEMAAAAoWU_HrrEnUqJJBZRSSyZiAACWF5QfgAAAA==/move?");
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            var body = @" {""destinationId"": """ + folderid + "\"}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            RestResponse response = (RestResponse)client.Execute(request, Method.POST);

            if (response.StatusCode.ToString().Contains("Created"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }
            else if (response.StatusCode.ToString().Contains("NotFound"))
            {
                messages = JsonConvert.DeserializeObject<Mail>("Mail Not Found");
            }

            return new Tuple<Mail, string>(messages, token);
        }
        public Tuple<Mail, string> GetFolders()
        {
            string token = getToken();
            Mail messages = new Mail();
            /**list mail folder**/
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders? $top =100");
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            RestResponse response = (RestResponse)client.Execute(request, Method.GET);
            if (response.StatusCode.ToString().Contains("OK"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }

            return new Tuple<Mail, string>(messages, token);
        }
        private Tuple<Mail, string> GetChildFolders()
        {
            string token = getToken();
            Mail messages = new Mail();
            /**list mail folder**/
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders/" + mailfoldename + "/childFolders? $top =100");
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            RestResponse response = (RestResponse)client.Execute(request, Method.GET);
            if (response.StatusCode.ToString().Contains("OK"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }

            return new Tuple<Mail, string>(messages, token);
        }
        private Tuple<Mail, string> GetChildChildFolders(string childfolder)
        {
            string token = getToken();
            Mail messages = new Mail();
            /**list mail folder**/
            // var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders/" + childfolder + "/childFolders? $top =100");
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders/" + childfolder + "/childFolders? $top =100");
            //https://graph.microsoft.com/v1.0/me/mailFolders/{SubFolder-id}/childFolders  
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            RestResponse response = (RestResponse)client.Execute(request, Method.GET);
            if (response.StatusCode.ToString().Contains("OK"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }

            return new Tuple<Mail, string>(messages, token);
        }
        public Tuple<SinglemailValue, string> GetMessages_ByID(string mailid,string parentid)
        {
            string token = getToken();
            SinglemailValue messages = new SinglemailValue();
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders/" + parentid + "/messages/" + mailid );
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            RestResponse response = (RestResponse)client.Execute(request, Method.GET);
            if (response.StatusCode.ToString().Contains("OK"))
            {
                messages = JsonConvert.DeserializeObject<SinglemailValue>(response.Content);
            }
            return new Tuple<SinglemailValue, string>(messages, token);
        }
        public string getToken()
        {
            var client = new RestClient("https://login.microsoftonline.com/" + Tenantid + "/oauth2/v2.0/token");
            var request = new RestRequest();
            request.AlwaysMultipartFormData = true;
            request.AddParameter("client_secret", Secretid); //"fm48Q~a3cl1oi5iB9OaCMjrqfUGolDb0H_YbGae5"
            request.AddParameter("grant_type", "client_credentials");
            request.AddParameter("scope", "https://graph.microsoft.com/.default");
            request.AddParameter("client_id", Clientid); //"b4e05ba0-4c99-4063-a0f5-103286abc29b"
            RestResponse response = (RestResponse)client.Execute(request, Method.POST);
            Token token = JsonConvert.DeserializeObject<Token>(response.Content);
            return token.access_token;
        }
        public Tuple<Mail, string> GetMessages()
        {
            string token = getToken();
            Mail messages = new Mail();
            //var client = new RestClient("https://graph.microsoft.com/v1.0/users/satya.dani@luminad.com/messages?$filter=from/emailAddress/address eq 'ramsenthil18@gmail.com'");
            /**1. Inbox, fromMailid, subject , asc order, Top**/
            // var client = new RestClient("https://graph.microsoft.com/v1.0/users/satya.dani@luminad.com/mailFolders/inbox/messages?$select=id,subject,from,body & $filter= from/emailAddress/address eq 'ramsenthil18@gmail.com' and contains(subject, 'Re: WKB Points for Senthil')  &  $top =1000");
            // var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders/" + mailfoldename + "/messages?$select=id,subject,from,body & $filter= from/emailAddress/address eq '" + from_address + "' and contains(subject, '" + subject + "')  &  $top =" + Top);
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders/" + mailfoldename + "/messages?$top =" + Top);
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            RestResponse response = (RestResponse)client.Execute(request, Method.GET);
            if (response.StatusCode.ToString().Contains("OK"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }
            return new Tuple<Mail, string>(messages, token);
        }
        public class folderdetails
        {
            public string displayname { get; set; }
            public string id { get; set; }
            public string parentFolderId { get; set; }
        }
        public class categoriesdetails
        {
            public string displayname { get; set; }
            public string color { get; set; }
            public string id { get; set; }
        }
        public Tuple<Mail, string> PostFolders(string foldername)
        {
            string token = getToken();
            Mail messages = new Mail();
            /**create mail folder**/
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders?");
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            var body = @" {""displayName"": """ + foldername + "\"}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            RestResponse response = (RestResponse)client.Execute(request, Method.POST);
            if (response.StatusCode.ToString().Contains("Created"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }

            return new Tuple<Mail, string>(messages, token);
        }
        public Tuple<Mail, string> PostChildFolders(string childfoldername, string parentfolderid)
        {
            string token = getToken();
            Mail messages = new Mail();
            /**create mail folder**/
            var client = new RestClient("https://graph.microsoft.com/v1.0/users/" + usersmailid + "/mailFolders/" + parentfolderid + "/childFolders?");
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Authorization", $"Bearer {token}");
            var body = @" {""displayName"": """ + childfoldername + "\"}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            RestResponse response = (RestResponse)client.Execute(request, Method.POST);
            if (response.StatusCode.ToString().Contains("Created"))
            {
                messages = JsonConvert.DeserializeObject<Mail>(response.Content);
            }
            return new Tuple<Mail, string>(messages, token);
        }
        public class messagedetails
        {
            public string subject { get; set; }
            public string from_email { get; set; }
            public string body { get; set; }
            public DateTime rec_date { get; set; }
            public string id { get; set; }
        }
    }
}
