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 System.Web.Services;
using System.IO;
using System.Text.RegularExpressions;

namespace ToolsCRM.user_sites
{
  
    public partial class Articles : System.Web.UI.Page
    {
        
        
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = Session["user"].ToString();
        }


        public void ShowNewArticles()
        {
            var xrm = new XrmServiceContext("Xrm");

            var competitors =
                from competitor in xrm.CompetitorSet
                select new
                {
                    Name = competitor.Name,
                    miasto = competitor.Address1_City,
                    kraj = competitor.Address1_Country
                };
            
           
            GridView1.DataSource = competitors;
            GridView1.DataBind();
           
        }

        //Metody statyczne nie przyjmują propertis z formy np TextBox rozwiazanie zastosowanie Generic Handler
        //Dodawnie do CRMA AJAX z formularza znajduje sie w Default.html kod cs Insertcompetitor.ashx
       
        [WebMethod]
        public static void AddNewArticle()
        {
            var xrm = new XrmServiceContext("Xrm");
            var konkurenci = new Competitor
            {
                Name= "Zabka", 
                Address1_City = "Torun",
                Address1_County = "Polska"
            };
            xrm.AddObject(konkurenci);
            xrm.SaveChanges();
            
        }
        public void InsertHtmlCode() 
        {
            StreamReader sr;
            string html;
            //sciezka bezwgledna poprawie pozniej
            sr = File.OpenText(@"d:\Studia\IV_rok\C#\crm\ToolsCRM\ToolsCRM\Default.html");
            html = sr.ReadToEnd();
            sr.Close();

            Regex start = new Regex(@"[\s\S]*<body[^<]*>", RegexOptions.IgnoreCase);
            html = start.Replace(html, "");
            Regex end = new Regex(@"</body[\s\S]*", RegexOptions.IgnoreCase);
            html = end.Replace(html, "");
            htmlbody.Text = html;
        
        }
        [WebMethod]
        public static string GetDate()
        {
            return DateTime.Now.ToString();
        }
        protected void Wyloguj_Click(object sender, EventArgs e)
        {
            Session["admin"] = null;
            Session["user"] = null;
            Response.Redirect("../Index.aspx");

        }
    }
}