using CommunicationWithApi.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace CommunicationWithApi
{
    internal class Program
    {
        private static string userName = "*********"; // نام کاربری 
        private static string password = "*********";  // رمز عبور
        private static string Baseurl = "https://mizeOnline.ir"; //آدرس سرویس  
        static void Main(string[] args)
        {

            var authResult = Login().Result;
            if (authResult != null && !string.IsNullOrEmpty(authResult.Token))
            {
                var invoiceResult = SendInvoice(authResult.Token).Result;
                if(invoiceResult != null)
                    foreach (var result in invoiceResult)
                    {
                        Console.WriteLine($"UniqueId:{result.UniqueId}");
                        Console.WriteLine($"TaxSerialNumber: {result.TaxSerialNumber}");
                        Console.WriteLine($"Description: {result.Description}");
                        Console.WriteLine($"Title: {result.Title}");
                        Console.WriteLine($"CommodityCode: {result.CommodityCode}");
                        Console.WriteLine($"-----------------------------------------------------------");
                    }
            }
            Console.ReadLine();
        }
        private static async Task<AuthenticationModel> Login()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Baseurl);

                var loginModle = new LoginViewModel() { UserName = userName, Password = password };

                var serializedContent = JsonConvert.SerializeObject(loginModle);

                var content = new StringContent(serializedContent, Encoding.UTF8, "application/json");

                var result = await client.PostAsync("/identity/api/ServiceToken", content);

                if (result.IsSuccessStatusCode)
                {
                    string resultContent = await result.Content.ReadAsStringAsync();
                    var responce = JsonConvert.DeserializeObject<Result<AuthenticationModel>>(resultContent);
                    if (responce.Error)
                        Console.WriteLine(responce.Message);
                    else
                        return responce.Data;
                }
                return null;
            }
        }
        private static async Task<List<InvoiceImportResult>> SendInvoice(string token)
        {
            var invoices = new List<Invoice>{new Invoice
            {
                UniqueId = Guid.NewGuid(),
                InvoiceNumber = "ApiTestInvoice2",
                InvoiceDate = DateTime.Now,
                InvoicePattern = 1,
                InvoiceType = 1,
                SaleType = 1,
                InvoiceSubject = 1,
                HasBuyerPaidTax = true,
                BuyerType = 1,
                BuyerNationalCode = "2741371547",
                InvoicePayments = new List<InvoicePayment>(),
                InvoiceItems = new List<InvoiceItem>() { new InvoiceItem
                    {
                        CommodityType= 1,
                        CommodityCode= "0815472280860001",
                        Amount= 1500,
                        UnitType=164,
                        UnitPrice= 15000.5M,
                        Discount= 0,
                        TaxPercent= 9,
                        MoneyType= 37,
                        EquivalentToRial= 1,
                        CurrencyAmount= 0,
                        DutyPercent= 0,
                        DutyPrice= 0,
                        OtherLegalFundsPercent= 0,
                        OtherLegalFundsPrice= 0,
                    } }
            } };

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Baseurl);


                var serializedContent = JsonConvert.SerializeObject(invoices, new JsonSerializerSettings
                {
                    ContractResolver = new DefaultContractResolver
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    },
                    Formatting = Formatting.Indented
                });

                var content = new StringContent(serializedContent, Encoding.UTF8, "application/json");

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

                var result = await client.PostAsync("/taxpayer/api/InvoiceExternalService_v6", content);

                if (result.IsSuccessStatusCode)
                {
                    string resultContent = await result.Content.ReadAsStringAsync();
                    var responce = JsonConvert.DeserializeObject<Result<List<InvoiceImportResult>>>(resultContent);
                    if (responce.Error)
                        Console.WriteLine(responce.Message);
                    else
                        return responce.Data;
                }
                return null;
            }
        }
    }

}
