using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WctCustomerApiSample.Api;
using WctCustomerApiSample.Model;
using WctCustomerApiSample.Utility;
using Newtonsoft.Json;

namespace WctCustomerApiSample.Example
{
    class GetAccounts:IExample
    {
        public String Brief()
        {            
            return "Get all accounts";
        }
        public void RunIt() {
            var settings = Properties.Settings.Default;

            AccountApiService accountService = new AccountApiService(settings.Host);

            LoginInfo loginInfo = LoginProcess(accountService);
            if (loginInfo == null) {
                return;
            }

            string token = loginInfo.tokenInfo.token;

            List<AccountInfoLess> accounts = accountService.getAccounts(token);
            if (accounts.IsNullOrEmpty()) {
                return;
            }

            Console.WriteLine("\r\nAccount list:");
            foreach (var account in accounts)
            {
                string json = JsonConvert.SerializeObject(account);
                Console.WriteLine(json);
            }

        }
        static public LoginInfo LoginProcess(AccountApiService accountService)
        {
            if (!accountService.isConnectable())
            {
                MessageBox.Show("Server is not connectable.");
                return null;
            }

            Console.WriteLine("\r\nPlease login first to get token, for calling APIs.");
            Console.WriteLine("\r\nEnter account: ");
            string name = Console.ReadLine();
            Console.WriteLine("\r\nEnter password: ");
            string password = Console.ReadLine();

            LoginInfo loginInfo = accountService.login(name, password);

            if (loginInfo==null)
            {
                MessageBox.Show("Login info is incorrect.");
                return null;
            }
            else
            {
                MessageBox.Show("Login success, returned token: " + loginInfo.tokenInfo.token);
            }

            return loginInfo;
        }
    }
}
