using Dal.SOFD;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Lib.Core.Model
{
    internal class OrgUnitService
    {
        private EmployeeService empService;
        private IRepo<v_orgunit> orgRepo;

        internal OrgUnitService(string connStr)
        {
            orgRepo = new OrgUnitRepo(connStr);
            empService = new EmployeeService(connStr);
        }

        internal OrgUnit GetOrgUnitFromID(string id)
        {
            v_orgunit orgunit = orgRepo.Query.Where(o => o.id == getInt(id)).FirstOrDefault();
            string idStr = id.ToString();
            if(orgunit != null)
            {
                OrgUnit _OrgUnit = new OrgUnit()
                {
                    uuid = orgunit.orguuid,
                    name = orgunit.longName,
                    employees = empService.GetEmployeesFromOrgId(idStr),
                    kle_interest = new List<string>(),
                    kle_performing = new List<string>(),
                    children = new List<OrgUnit>()
                };

                return _OrgUnit;
            }
            else
            {
                throw new Exception("Orgunit not found, id: " + id);
            }
        }

        private int? getInt(string val)
        {
            int i;
            return int.TryParse(val, out i) ? i : default(int?);
        }

    }
}
