using System;
using Xunit;
using Newtonsoft.Json.Linq;
using FluentAssertions;

namespace raven_integration
{

    public class WidgetCrud
    {

        /// <summary>
        /// Test all CRUD routes for a widget
        /// </summary>       
        [Fact]
        public async void CRUD()
        {
            /*  
            {
                "id": 0,
                "name": "string",
                "dollarAmount": 0,
                "active": true,
                "roles": 0
            }
               */
            //CREATE
            dynamic w1 = new JObject();
            w1.name = Util.Uniquify("First Test WIDGET");
            w1.dollarAmount = 1.11m;
            w1.active = true;
            w1.roles = 0;
            w1.notes = "The quick brown fox jumped over the six lazy dogs!";

            //Tags 
            dynamic dTagsArray = new JArray();
            dTagsArray.Add("Red Tag");
            dTagsArray.Add("ORANGE   IS  THE  NEW      BLACK");
            dTagsArray.Add("yellow");
            dTagsArray.Add("green");
            dTagsArray.Add("blue");
            dTagsArray.Add("indigo");
            dTagsArray.Add("VIOLET Tag");
            w1.tags = dTagsArray;

            ApiResponse r1 = await Util.PostAsync("Widget", await Util.GetTokenAsync("manager", "l3tm3in"), w1.ToString());
            Util.ValidateDataReturnResponseOk(r1);
            long w1Id = r1.ObjectResponse["data"]["id"].Value<long>();

            dynamic w2 = new JObject();
            w2.name = Util.Uniquify("Second Test WIDGET");
            w2.dollarAmount = 2.22m;
            w2.active = true;
            w2.roles = 0;
            w2.notes = "What is the frequency Kenneth?";
            w2.tags = dTagsArray;

            ApiResponse r2 = await Util.PostAsync("Widget", await Util.GetTokenAsync("manager", "l3tm3in"), w2.ToString());
            Util.ValidateDataReturnResponseOk(r2);
            long w2Id = r2.ObjectResponse["data"]["id"].Value<long>();

            //RETRIEVE

            //Get one
            ApiResponse r3 = await Util.GetAsync("Widget/" + w2Id.ToString(), await Util.GetTokenAsync("manager", "l3tm3in"));
            Util.ValidateDataReturnResponseOk(r3);
            r3.ObjectResponse["data"]["name"].Value<string>().Should().Be(w2.name.ToString());
            r3.ObjectResponse["data"]["notes"].Value<string>().Should().Be(w2.notes.ToString());
            var returnedTags = ((JArray)r3.ObjectResponse["data"]["tags"]);
            returnedTags.Count.Should().Be(7);
            returnedTags[0].Value<string>().Should().Be("red-tag");
            returnedTags[1].Value<string>().Should().Be("orange-is-the-new-black");
            returnedTags[2].Value<string>().Should().Be("yellow");
            returnedTags[3].Value<string>().Should().Be("green");
            returnedTags[4].Value<string>().Should().Be("blue");
            returnedTags[5].Value<string>().Should().Be("indigo");
            returnedTags[6].Value<string>().Should().Be("violet-tag");



            //UPDATE
            //PUT

            //update w2id 
            w2.name = Util.Uniquify("UPDATED VIA PUT SECOND TEST WIDGET");
            w2.OwnerId = 1;
            w2.concurrencyToken = r2.ObjectResponse["data"]["concurrencyToken"].Value<uint>();
            ApiResponse PUTTestResponse = await Util.PutAsync("Widget/" + w2Id.ToString(), await Util.GetTokenAsync("manager", "l3tm3in"), w2.ToString());
            Util.ValidateHTTPStatusCode(PUTTestResponse, 200);

            //check PUT worked
            ApiResponse checkPUTWorked = await Util.GetAsync("Widget/" + w2Id.ToString(), await Util.GetTokenAsync("manager", "l3tm3in"));
            Util.ValidateNoErrorInResponse(checkPUTWorked);
            checkPUTWorked.ObjectResponse["data"]["name"].Value<string>().Should().Be(w2.name.ToString());
            uint concurrencyToken = PUTTestResponse.ObjectResponse["data"]["concurrencyToken"].Value<uint>();

            //PATCH
            var newName = Util.Uniquify("UPDATED VIA PATCH SECOND TEST WIDGET");
            string patchJson = "[{\"value\": \"" + newName + "\",\"path\": \"/name\",\"op\": \"replace\"}]";
            ApiResponse PATCHTestResponse = await Util.PatchAsync("Widget/" + w2Id.ToString() + "/" + concurrencyToken.ToString(), await Util.GetTokenAsync("manager", "l3tm3in"), patchJson);
            Util.ValidateHTTPStatusCode(PATCHTestResponse, 200);

            //check PATCH worked
            ApiResponse checkPATCHWorked = await Util.GetAsync("Widget/" + w2Id.ToString(), await Util.GetTokenAsync("manager", "l3tm3in"));
            Util.ValidateNoErrorInResponse(checkPATCHWorked);
            checkPATCHWorked.ObjectResponse["data"]["name"].Value<string>().Should().Be(newName);

            //DELETE
            ApiResponse DELETETestResponse = await Util.DeleteAsync("Widget/" + w2Id.ToString(), await Util.GetTokenAsync("manager", "l3tm3in"));
            Util.ValidateHTTPStatusCode(DELETETestResponse, 204);
        }






        /// <summary>
        /// Test not found
        /// </summary>       
        [Fact]
        public async void GetNonExistentItemShouldError()
        {
            //Get non existant
            //Should return status code 404, api error code 2010
            ApiResponse a = await Util.GetAsync("Widget/999999", await Util.GetTokenAsync("manager", "l3tm3in"));
            Util.ValidateResponseNotFound(a);
        }

        /// <summary>
        /// Test bad modelstate
        /// </summary>       
        [Fact]
        public async void GetBadModelStateShouldError()
        {
            //Get non existant
            //Should return status code 400, api error code 2200 and a first target in details of "id"
            ApiResponse a = await Util.GetAsync("Widget/2q2", await Util.GetTokenAsync("manager", "l3tm3in"));
            Util.ValidateBadModelStateResponse(a, "id");
        }


        /// <summary>
        /// Test server exception
        /// </summary>       
        [Fact]
        public async void ServerExceptionShouldErrorPropertly()
        {
            //Get non existant
            //Should return status code 400, api error code 2200 and a first target in details of "id"
            ApiResponse a = await Util.GetAsync("Widget/exception", await Util.GetTokenAsync("manager", "l3tm3in"));
            Util.ValidateServerExceptionResponse(a);
        }



        /// <summary>
        /// Test server alt exception
        /// </summary>       
        [Fact]
        public async void ServerAltExceptionShouldErrorPropertly()
        {
            //Get non existant
            //Should return status code 400, api error code 2200 and a first target in details of "id"
            ApiResponse a = await Util.GetAsync("Widget/altexception", await Util.GetTokenAsync("manager", "l3tm3in"));
            Util.ValidateServerExceptionResponse(a);
        }




        /// <summary>
        /// 
        /// </summary>       
        [Fact]
        public async void PutConcurrencyViolationShouldFail()
        {

            //CREATE

            dynamic w2 = new JObject();
            w2.name = Util.Uniquify("PutConcurrencyViolationShouldFail");
            w2.dollarAmount = 2.22m;
            w2.active = true;
            w2.roles = 0;

            ApiResponse r2 = await Util.PostAsync("Widget", await Util.GetTokenAsync("manager", "l3tm3in"), w2.ToString());
            Util.ValidateDataReturnResponseOk(r2);
            long w2Id = r2.ObjectResponse["data"]["id"].Value<long>();
            uint OriginalConcurrencyToken = r2.ObjectResponse["data"]["concurrencyToken"].Value<uint>();



            //UPDATE
            //PUT

            w2.name = Util.Uniquify("PutConcurrencyViolationShouldFail UPDATE VIA PUT ");
            w2.OwnerId = 1;
            w2.concurrencyToken = OriginalConcurrencyToken - 1;//bad token
            ApiResponse PUTTestResponse = await Util.PutAsync("Widget/" + w2Id.ToString(), await Util.GetTokenAsync("manager", "l3tm3in"), w2.ToString());
            Util.ValidateConcurrencyError(PUTTestResponse);


        }




        /// <summary>
        /// 
        /// </summary>       
        [Fact]
        public async void PatchConcurrencyViolationShouldFail()
        {

            //CREATE

            dynamic w2 = new JObject();
            w2.name = Util.Uniquify("PatchConcurrencyViolationShouldFail");
            w2.dollarAmount = 2.22m;
            w2.active = true;
            w2.roles = 0;

            ApiResponse r2 = await Util.PostAsync("Widget", await Util.GetTokenAsync("manager", "l3tm3in"), w2.ToString());
            Util.ValidateDataReturnResponseOk(r2);
            long w2Id = r2.ObjectResponse["data"]["id"].Value<long>();
            uint OriginalConcurrencyToken = r2.ObjectResponse["data"]["concurrencyToken"].Value<uint>();


            //PATCH
            var newName = Util.Uniquify("PutConcurrencyViolationShouldFail UPDATED VIA PATCH");
            string patchJson = "[{\"value\": \"" + newName + "\",\"path\": \"/name\",\"op\": \"replace\"}]";
            ApiResponse PATCHTestResponse = await Util.PatchAsync("Widget/" + w2Id.ToString() + "/" + (OriginalConcurrencyToken - 1).ToString(), await Util.GetTokenAsync("manager", "l3tm3in"), patchJson);
            Util.ValidateConcurrencyError(PATCHTestResponse);
        }





        //==================================================

    }//eoc
}//eons
