﻿/*
Copyright 2011 Google Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NUnit.Framework;

namespace Google.Apis.Tests.Apis
{
    [TestFixture()]
    public class OAuthUtilTest
    {
        [Test()]
        public void GenerateOAuth2HeaderTest_nonEmptyToken()
        {
            string token = "ADFWEB2324deoi34/";
            string expectedHeader = "Authorization: OAuth " + token;
            Assert.AreEqual(expectedHeader, OAuthUtil.GenerateOAuth2Header(token));
        }

        [Test()]
        public void GenerateOAuth2HeaderTest_emptyToken()
        {
            string token = "";
            string expectedHeader = "";
            Assert.AreEqual(expectedHeader, OAuthUtil.GenerateOAuth2Header(token));
        }

        [Test()]
        public void GenerateOAuth2HeaderTest_nullToken()
        {
            string token = null;
            string expectedHeader = "";
            Assert.AreEqual(expectedHeader, OAuthUtil.GenerateOAuth2Header(token));
        }
        
        /// <summary>
        /// Checks whether the time stamp generated by the GenerateTimestamp() method is a plausible UNIX timestamp
        /// </summary>
        [Test]
        public void GenerateTimeStampTest()
        {
            // Generate a Timestamp, and fetch the creation time of the timestamp for later comparison
            var util = new OAuthUtil();
            var srcTime = DateTime.UtcNow;
            string timestamp = util.GenerateTimeStamp();
            
            // Ensure that the generated timestamp is a whole number
            long unixTime;
            Assert.That(long.TryParse(timestamp, out unixTime), Is.True);
            
            // Convert the UNIX timestamp to a .NET DateTime
            var parsedTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(unixTime);
            TimeSpan timeDifference = parsedTime - srcTime;
            
            // Check whether the timestamp represents the current time
            Assert.That((long)Math.Abs(timeDifference.TotalSeconds), Is.EqualTo(0));
        }
    }
}
