using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Xrm;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;

namespace ToolsCRM.user_sites
{
    public partial class Contacts : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var xrm = new XrmServiceContext("Xrm");
                //.Where(c => c.EMailAddress1.EndsWith("@example.com"));
            var contacts =
                (from u in xrm.new_uzytkownikkontaktySet
                 join uzyt in xrm.new_uzytkownicySet on u.new_Uzytkownik.Id equals uzyt.new_uzytkownicyId
                 join kon in xrm.ContactSet on u.new_Kontakt.Id equals kon.ContactId
                 where uzyt.new_name == Session["user"].ToString()
                 select kon);
    
   

            GridView1.DataSource = contacts;    
            GridView1.DataBind();            

            if (Session["user"] == null)
                Response.Redirect("../error.aspx");
            else
            {
                Label1.Text = Session["user"].ToString();
               
            }
        }

        protected void Wyloguj_Click(object sender, EventArgs e)
        {
            Session["admin"] = null;
            Session["user"] = null;
            Response.Redirect("../Index.aspx");
        }

        protected void GridView1_DataBound(object sender, EventArgs e)
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                if (GridView1.Rows[i].Cells[6].Text == "0")
                    GridView1.Rows[i].Cells[6].Text = "aktywny";
                else
                    GridView1.Rows[i].Cells[6].Text = "nieaktywny";
            }
        }

        protected void Add_Click(object sender, EventArgs e)
        {
            Table1.Visible = true;
            Ed.Visible = false;
            Del.Visible = false;
            DropDownList1.Visible = false;
            Addadd.Visible = true;
            Label4.Text = "Dodaj nowy kotakt do bazy CRM";

            Label2.Visible = true;
            dodawanieKontaktu.Visible = true;
            Addadd2.Visible = true;
            Label3.Visible = true;
        }

        protected void Addadd_Click(object sender, EventArgs e)
        {
            if (Timie.Text != "" && Tnazwisko.Text != "" && Temail.Text != "" && Tmiasto.Text != "")
            {
                var xrm = new XrmServiceContext("Xrm");
                try
                {
                    var istniejacyKontakt = xrm.ContactSet.Where
                        (c =>
                        c.FirstName == Timie.Text &&
                        c.LastName == Tnazwisko.Text &&
                        c.EMailAddress1 == Temail.Text
                        ).Single();
                

                }
                catch (InvalidOperationException)
                {
                    var contact = new Contact
                    {
                        FirstName = Timie.Text,
                        LastName = Tnazwisko.Text,
                        EMailAddress1 = Temail.Text,
                        Address1_City = Tmiasto.Text                        
                    };
                    xrm.AddObject(contact);
                    xrm.SaveChanges();
                    GridView1.DataBind();
                    Table1.Visible = false;
                    return;
                }
                Label4.Text = "Podany rekord już istnieje w bazie CRM!";
            }
            Table1.Visible = false;
        }

        protected void Addadd2_Click(object sender, EventArgs e)
        {
            var xrm = new XrmServiceContext("Xrm");
            string[] mejl = dodawanieKontaktu.SelectedItem.Value.Split(' ');
            string szukana = mejl[mejl.Length - 1];

            try
            {     
            var istniejacyKontakt1 =
            (from u in xrm.new_uzytkownikkontaktySet
             join uzyt in xrm.new_uzytkownicySet on u.new_Uzytkownik.Id equals uzyt.new_uzytkownicyId
             join kon in xrm.ContactSet on u.new_Kontakt.Id equals kon.ContactId
             where kon.EMailAddress1 == szukana
             select new{
             nazu=uzyt.new_nazwisko,nazk=kon.LastName,nazwp=u.new_name,login=uzyt.new_name
             }
             );

            var istniejacyKontakt2 =(from q in istniejacyKontakt1.ToList()
                                      where q.login == Session["user"].ToString()
                                      select q.nazwp).Single();
            }
            catch (InvalidOperationException)
            {
                var istniejacyUzytkownik =
                (from uzyt in xrm.new_uzytkownicySet
                 where uzyt.new_name == Session["user"].ToString()
                 select uzyt);

                var istniejacyKontakt =
                    (from kon in xrm.ContactSet
                     where kon.EMailAddress1 == szukana
                     select kon);

                Guid userId = new Guid();
                foreach (var s in istniejacyUzytkownik)
                {
                    userId = s.Id;                  
                }
                Guid contactId = new Guid();
                foreach (var s in istniejacyKontakt)
                {
                    contactId = s.Id;
                }
                

                EntityReference primaryUzytkownikId = new EntityReference("new_Uzytkownik", userId);
                EntityReference primaryKontaktId = new EntityReference("new_Kontakt", contactId);
                
                var nowePolaczenie = new new_uzytkownikkontakty
                {
                    
                    new_Uzytkownik = primaryUzytkownikId,
                    new_Kontakt = primaryKontaktId,
                    new_name = istniejacyUzytkownik.Single().new_name + "_" + istniejacyKontakt.Single().EMailAddress1
                };
                xrm.AddObject(nowePolaczenie);
                
                xrm.SaveChanges();
                GridView1.DataBind();
                Table1.Visible = false;
                return;
            }
            Label3.Text = "Podany rekord już istnieje w Twoich kontaktach!";
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            Table1.Visible = false;
            Ed.Visible = false;
            DropDownList1.Visible = true;
            Del.Visible = true;
            Label4.Text = "";
            Label2.Text = "";
            dodawanieKontaktu.Visible = false;
            Addadd2.Visible = false;
            Label3.Visible = false;
        }

        protected void Del_Click(object sender, EventArgs e)
        {
                string[] mejl = DropDownList1.SelectedItem.Value.Split(' ');
                string szukana = mejl[mejl.Length - 1];

                var xrm = new XrmServiceContext("Xrm");
                var contact = xrm.ContactSet.Where(c => c.EMailAddress1 == szukana).FirstOrDefault();

                xrm.DeleteObject(contact);
                xrm.SaveChanges();
                GridView1.DataBind();
                
            Del.Visible = false;
            DropDownList1.Visible = false;            
        }

        protected void Edit_Click(object sender, EventArgs e)
        {
            Del.Visible = false;
            DropDownList1.Visible = true;
            Ed.Visible = true;
            Table1.Visible = true;
            Addadd.Visible = false;
            GridView1.DataBind();
            Label4.Text = "";
            Label2.Text = "";
            dodawanieKontaktu.Visible = false;
            Addadd2.Visible = false;
            Label3.Visible = false;
        }

        protected void Ed_Click(object sender, EventArgs e)
        {
            if (Timie.Text != "" && Tnazwisko.Text != "" && Temail.Text != "" && Tmiasto.Text != "")
            {
                var xrm = new XrmServiceContext("Xrm");
                try
                {
                    var istniejacyKontakt = xrm.ContactSet.Where
                        (c =>
                        c.FirstName == Timie.Text &&
                        c.LastName == Tnazwisko.Text &&
                        c.EMailAddress1 == Temail.Text &&
                        c.Address1_City == Tmiasto.Text
                        ).Single();
                }
                catch (InvalidOperationException)
                {
                    string[] mejl = DropDownList1.SelectedItem.Value.Split(' ');
                    string szukana = mejl[mejl.Length - 1];
                    var contact = xrm.ContactSet.Where(c => c.EMailAddress1 == szukana).Single();
                    contact.FirstName = Timie.Text;
                    contact.LastName = Tnazwisko.Text;
                    contact.EMailAddress1 = Temail.Text;
                    contact.Address1_City = Tmiasto.Text;

                    xrm.UpdateObject(contact);
                    xrm.SaveChanges();
                    GridView1.DataBind();
                    Table1.Visible = false;
                    return;
                }
                Label4.Text = "Podany rekord już istnieje!";
            }
            Table1.Visible = false;
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var xrm = new XrmServiceContext("Xrm");

            string[] mejl = DropDownList1.SelectedItem.Value.Split(' ');
            string szukana = mejl[mejl.Length - 1];
            var zawartoscTextbox = (from contacty in xrm.ContactSet
                                    where contacty.EMailAddress1 == szukana
                                    select new { imie = contacty.FirstName, nazwisko = contacty.LastName, email = contacty.EMailAddress1, miasto = contacty.Address1_City });

            foreach (var g in zawartoscTextbox)
            {
                Timie.Text = g.imie;
                Tnazwisko.Text = g.nazwisko;
                Temail.Text = g.email;
                Tmiasto.Text = g.miasto;
            }
        }

        protected void DropDownList1_Init(object sender, EventArgs e)
        {

            var xrm = new XrmServiceContext("Xrm");
            var contactList =
                (from contacty in xrm.ContactSet
                 select new { imie = contacty.FirstName, nazwisko = contacty.LastName, email = contacty.EMailAddress1 });

            
            foreach (var v in contactList)
            {
                DropDownList1.Items.Add(v.imie + " " + v.nazwisko + "    " + v.email);
            }
        }

        protected void dodawanieKontaktu_Init(object sender, EventArgs e)
        {
            var xrm = new XrmServiceContext("Xrm");
            var contactList =
                (from contacty in xrm.ContactSet
                 select new { imie = contacty.FirstName, nazwisko = contacty.LastName, email = contacty.EMailAddress1 });


            foreach (var v in contactList)
            {
                dodawanieKontaktu.Items.Add(v.imie + " " + v.nazwisko + "    " + v.email);
            }
        }
    }
}