using System;
using System.Collections.Generic;
using Model;
using Telerik.OpenAccess;
using Telerik.OpenAccess.Query;

namespace ConsoleApp
{
  class Program
  {
    static void Main(string[] args)
    {
      using (IObjectScope scope = ObjectScopeProvider1.GetNewObjectScope())
      {
        scope.TransactionProperties.AutomaticBegin = true;

        HandleOrders(scope);

        List<Employee> employees = scope.Extent<Employee>().ToList();

        ShowEmployeeTerritories(employees);

        ShowEmployeeHierarchy(employees);

        Console.ReadLine();
      }
    }

    private static void ShowEmployeeHierarchy(List<Employee> employees)
    {
      foreach (Employee employee in employees)
      {
        Console.Write(employee.FirstName + " " +
          employee.LastName);
        if (employee.ReportsToEmployee != null)
        {
          Console.WriteLine(" reports to " +
            employee.ReportsToEmployee.FirstName + " " +
            employee.ReportsToEmployee.LastName);
        }
        if (employee.Subordinates.Count > 0)
        {
          Console.WriteLine("\tEmployees:");
          foreach (Employee emp in employee.Subordinates)
          {
            Console.WriteLine("\t\t" + emp.FirstName + " " + emp.LastName);
          }
        }
      }
    }

    private static void ShowEmployeeTerritories(List<Employee> employees)
    {
      foreach (Employee employee in employees)
      {
        Console.WriteLine(employee.FirstName + " " + employee.LastName);
        foreach (Territory territory in employee.EmployeeTerritories)
        {
          Console.WriteLine("\tEmployees for territory: " +
            territory.TerritoryDescription);
          foreach (Employee emp in territory.Employees)
          {
            Console.WriteLine("\t\t" + emp.FirstName + " " + emp.LastName);
          }
        }
      }
    }

    private static void HandleOrders(IObjectScope scope)
    {
      Order order = new Order();
      order.CustomerID = "CHOPS";
      order.RequiredDate = DateTime.Today.AddDays(14);
      scope.Add(order);
      // commit the order to get the OrderID
      scope.Transaction.Commit();

      // add the order details
      OrderDetail detail1 = new OrderDetail();
      detail1.OrderID = order.OrderID;
      detail1.ProductID = 2;
      detail1.Discount = 0.1f;
      detail1.Quantity = 3;
      detail1.UnitPrice = 19m;
      order.OrderDetails.Add(detail1);

      OrderDetail detail2 = new OrderDetail();
      detail2.OrderID = order.OrderID;
      detail2.ProductID = 5;
      detail2.Quantity = 1;
      detail2.UnitPrice = 21.35m;
      order.OrderDetails.Add(detail2);

      scope.Add(detail1);
      scope.Add(detail2);
      scope.Transaction.Commit();

      foreach (OrderDetail detail in order.OrderDetails)
      {
        Console.WriteLine(detail.Order.OrderID);
        Console.WriteLine(detail.ProductID);
      }
    }
  }
}
