using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using WPF_Sample.Common;

namespace WPF_Sample.Views.Tools
{
    /// <summary>
    /// Interaction logic for TokenGenerator.xaml
    /// </summary>
    public partial class TokenGenerator : Page
    {
        
        //Time in seconds
        const int secondsCounterMax = 3600;  
        private DispatcherTimer postTimer = new DispatcherTimer();
        private int secondsCounter;
        
        private string textFilePath;

        public TokenGenerator()
        {
            InitializeComponent();
            URL.Text = "https://stratustime.centralservers.com/Service/ws-json/1.0/TokenCreate";
            textFilePath = System.AppDomain.CurrentDomain.BaseDirectory;
            secondsCounter = secondsCounterMax;
            LocationPath.Text = textFilePath;
        }

        private void PostButton_Click(object sender, RoutedEventArgs e)
        {
            PostResult.Text = "Loading Please Wait...";
            AppUtil.DoEvents();

            Func<HttpWebResponse, string> getResponse = (response) =>
            {
                var responseEncoding = Encoding.GetEncoding(response.CharacterSet);
                using (var sr = new StreamReader(response.GetResponseStream(), responseEncoding))
                {
                    return sr.ReadToEnd();
                }
            };

            string jsonContent = PostData.Text;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL.Text);
            request.Method = "POST";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            Byte[] byteArray = encoding.GetBytes(jsonContent);

            request.ContentLength = byteArray.Length;
            request.ContentType = @"application/json";

            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }

            long length = 0;

            try
            {
                string body;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    length = response.ContentLength;
                    body = getResponse(response);
                }
                PostResult.Text = body;
                File.WriteAllText(String.Format(@"{0}\TokenGenerator.txt", textFilePath), body);

                if (CheckBoxAutoGenerate.IsChecked == true)
                {
                    stopTokenGenerator();
                    startTokenGenerator();
                }

            }
            catch (WebException ex)
            {
                PostResult.Text = "Be Sure to check the full URL:" + ex.ToString();
            }
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            PostData.Text = @"{
	""CustomerAlias"":""YOUR-ALIAS"",
	""SharedKey"":""234f710d-894f-44f2-9012-8598a09f4777"",
	""UserName"":""wsuser"",
	""UserPass"":""YOUR-PASS""
}";

        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            startTokenGenerator();
        }

        private void CheckBox_UnChecked(object sender, RoutedEventArgs e)
        {
            stopTokenGenerator();
        }

        private void postTimer_Tick(object sender, EventArgs e)
        {
            TimeSpan time = TimeSpan.FromSeconds(secondsCounter);
            CountdownLabel.Content = time.ToString(@"hh\:mm\:ss");
            if (secondsCounter >= secondsCounterMax || secondsCounter == 0)
            {
                PostResult.Text = "";
                PostButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
                secondsCounter = secondsCounterMax;

            }
           
            secondsCounter--;
        }

        private void startTokenGenerator()
        {
            postTimer.Tick += postTimer_Tick;
            postTimer.Interval = new TimeSpan(0, 0, 1);
            postTimer.Start();
        }

        private void stopTokenGenerator()
        {
            postTimer.Tick -= postTimer_Tick;
            secondsCounter = secondsCounterMax;
        }

        private void OpenLocation_Click(object sender, RoutedEventArgs e)
        {
            Process.Start(textFilePath);
        }

    }
}
