// Autogenerated with DRAKON Editor 1.25
using System;
using System.Linq;
using System.Collections.Generic;

class Bar {
	public delegate void AnyCode();

	private class FakeDepartment : IDepartment {
		public int Id { get; set; }
		public string Title { get; set; }
	}
    public interface IBaseRecord
    {
        int Id { get; }
    }
    private interface IDelRecord
    {
        void PreDeleteOuter(System.Collections.Generic.HashSet<IDelRecord> deletionList, bool master);
        void EnsureCanDelete(System.Collections.Generic.HashSet<IDelRecord> deletionList);
        void DoDelete(Bar db, System.Collections.Generic.HashSet<IDelRecord> deletionList);
    }
    public interface IEmployee : IBaseRecord {
        string Name { get; }
        IDepartment Department { get; }
    }
    public interface IDepartment : IBaseRecord {
        string Title { get; }
    }
    public interface ICompany : IBaseRecord {
        IDepartment Marketing { get; }
    }
    private int _next_employee = 1;
    private readonly Dictionary<int, Employee> _employee_pk = new Dictionary<int, Employee>();
    private int _next_department = 1;
    private readonly Dictionary<int, Department> _department_pk = new Dictionary<int, Department>();
    private int _next_company = 1;
    private readonly Dictionary<int, Company> _company_pk = new Dictionary<int, Company>();
    private class Employee_Department_Name_Comparer : IEqualityComparer<Employee> {
        public bool Equals(Employee x, Employee y) {
            if (x._department != null && y._department != null) {
                if (x._department._id != y._department._id) return false;
            } else {
                if (!Object.ReferenceEquals(x._department, y._department)) return false;
            }
            if (!Object.Equals(x._name, y._name)) return false;
            return true;
        }
        public int GetHashCode(Employee obj) {
            int code = ((obj._department == null) ? 0 : obj._department._id.GetHashCode());
            code = (code * 397) ^ ((obj._name == null) ? 0 : obj._name.GetHashCode());
            return code;
        }
    }
    private readonly Dictionary<Employee, Employee> _employee_Department_Name = new Dictionary<Employee, Employee>(new Employee_Department_Name_Comparer());
    private class Department_Title_Comparer : IEqualityComparer<Department> {
        public bool Equals(Department x, Department y) {
            if (!Object.Equals(x._title, y._title)) return false;
            return true;
        }
        public int GetHashCode(Department obj) {
            int code = ((obj._title == null) ? 0 : obj._title.GetHashCode());
            return code;
        }
    }
    private readonly Dictionary<Department, Department> _department_Title = new Dictionary<Department, Department>(new Department_Title_Comparer());
    private class Employee : IEmployee, IDelRecord {
        public readonly int _id;
        public int Id { get { return _id; } }
        public Employee(int id) {
            _id = id;
        }
        public string _name;
        public string Name {
            get { return _name; }
        }
        public Department _department;
        public IDepartment Department {
            get { return _department; }
        }
        public virtual void EnsureCanDelete(System.Collections.Generic.HashSet<IDelRecord> deletionList) {
        }
        public virtual void DoDelete(Bar db, System.Collections.Generic.HashSet<IDelRecord> deletionList) {
            if (_department != null ) {
                if ( !deletionList.Contains(_department)) {
                    _department._refCount--;
                }
            }
            db._employee_Department_Name.Remove(this);
            db._employee_pk.Remove(_id);
        }
        public virtual void PreDeleteOuter(System.Collections.Generic.HashSet<IDelRecord> deletionList, bool master) {
            if (deletionList.Contains(this)) {
                return;
            } else {
                deletionList.Add(this);
            }
            PreDeleteInner(deletionList);
        }
        public virtual void PreDeleteInner(System.Collections.Generic.HashSet<IDelRecord> deletionList) {
        }
    }
    private readonly Employee _employee_Key = new Employee(0);
    private class Department : IDepartment, IDelRecord {
        public readonly int _id;
        public int Id { get { return _id; } }
        public Department(int id) {
            _id = id;
        }
        public int _refCount = 0;
        public string _title;
        public string Title {
            get { return _title; }
        }
        public virtual void EnsureCanDelete(System.Collections.Generic.HashSet<IDelRecord> deletionList) {
        }
        public virtual void DoDelete(Bar db, System.Collections.Generic.HashSet<IDelRecord> deletionList) {
            db._department_Title.Remove(this);
            db._department_pk.Remove(_id);
        }
        public virtual void PreDeleteOuter(System.Collections.Generic.HashSet<IDelRecord> deletionList, bool master) {
            if (deletionList.Contains(this)) {
                return;
            } else {
                deletionList.Add(this);
            }
            if ( master && _refCount > 1 || 
              !master && _refCount > 0 ) {
                string className = GetType().Name;
                throw new ArgumentException(String.Format(
                    "'{0}' with id '{1}' is referenced by other record.",
                    className, _id));
            }
            PreDeleteInner(deletionList);
        }
        public virtual void PreDeleteInner(System.Collections.Generic.HashSet<IDelRecord> deletionList) {
        }
    }
    private readonly Department _department_Key = new Department(0);
    private class Company : ICompany, IDelRecord {
        public readonly int _id;
        public int Id { get { return _id; } }
        public Company(int id) {
            _id = id;
        }
        public Department _marketing;
        public IDepartment Marketing {
            get { return _marketing; }
        }
        public virtual void EnsureCanDelete(System.Collections.Generic.HashSet<IDelRecord> deletionList) {
        }
        public virtual void DoDelete(Bar db, System.Collections.Generic.HashSet<IDelRecord> deletionList) {
            if (_marketing != null ) {
                if ( !deletionList.Contains(_marketing)) {
                    _marketing._refCount--;
                }
            }
            db._company_pk.Remove(_id);
        }
        public virtual void PreDeleteOuter(System.Collections.Generic.HashSet<IDelRecord> deletionList, bool master) {
            if (deletionList.Contains(this)) {
                return;
            } else {
                deletionList.Add(this);
            }
            PreDeleteInner(deletionList);
        }
        public virtual void PreDeleteInner(System.Collections.Generic.HashSet<IDelRecord> deletionList) {
            if ( Marketing != null ) {
                _marketing.PreDeleteOuter(deletionList, true);
            }
        }
    }
    public IEmployee InsertEmployee(int id, string name, IDepartment department) {
        if ( id == 0 ) {
            id = _next_employee;
        } else {
            if (_employee_pk.ContainsKey(id)) {
                string className = _employee_pk[id].GetType().Name;
                throw new ArgumentException(String.Format(
                    "'{0}' with id '{1}' already exists.",
                    className, id));
            }
        }
        if ( id >= _next_employee ) {
            _next_employee = id + 1;
        }
        _employee_Key._department = (Department)department;
        _employee_Key._name = name;
        if ( _employee_Department_Name.ContainsKey(_employee_Key)) {
            throw new ArgumentException(
              "Fields 'Department Name' are not unique for 'Employee'.");
        }
        Department _department_;
        if (department == null ) {
            _department_ = null;
        } else if (!_department_pk.TryGetValue(department.Id, out _department_)) {
            throw new ArgumentException(String.Format(
                "'Department' with id '{0}' does not exist.",
                department.Id));
        }
        var _record_ = new Employee(id);
        _record_._name = name;
        _record_._department = _department_;
        _employee_pk[id] = _record_;
        _employee_Department_Name[_record_] = _record_;
        if (_record_._department != null ) {
            _record_._department._refCount++;
        }
        return _record_;
    }
    public IEmployee GetEmployee(int id) {
        Employee _record_;
        if (!_employee_pk.TryGetValue(id, out _record_)) {
            return null;
        }
        return _record_;
    }
    public int EmployeeCount() {
        return _employee_pk.Count;
    }
    public IEnumerable<IEmployee> EachEmployee() {
        foreach (KeyValuePair<int, Employee> record in _employee_pk) {
            yield return record.Value;
        }
    }
    public void DeleteEmployee(IEmployee record) {
        if (record == null) return;
        Employee _record_;
        var deletionList = new System.Collections.Generic.HashSet<IDelRecord>();
        if ( !_employee_pk.TryGetValue(record.Id, out _record_)) {
            throw new ArgumentException(String.Format(
                "'Employee' with id '{0}' does not exist.",
                record.Id));
        }
        _record_.PreDeleteOuter(deletionList, false);
        foreach (IDelRecord item in deletionList) {
            item.EnsureCanDelete(deletionList);
        }
        foreach (IDelRecord item in deletionList) {
            item.DoDelete(this, deletionList);
        }
    }
    public IEmployee FindEmployeeByDepartmentName(IDepartment department, string name) {
        Employee _record_;
        _employee_Key._department = (Department)department;
        _employee_Key._name = name;
        if (_employee_Department_Name.TryGetValue(_employee_Key, out _record_)) {
            return _record_;
        } else {
            return null;
        }
    }
    public void SetEmployeeName(IEmployee record, string newValue) {
        Employee _record_;
        if ( !_employee_pk.TryGetValue(record.Id, out _record_)) {
            throw new ArgumentException(String.Format(
                "'Employee' with id '{0}' does not exist.",
                record.Id));
        }
        if (Object.Equals(_record_._name, newValue)) {
            return;
        }
        _employee_Key._department = _record_._department;
        _employee_Key._name = newValue;
        if ( _employee_Department_Name.ContainsKey(_employee_Key)) {
            throw new ArgumentException(
              "Fields 'Department Name' are not unique for 'Employee'.");
        }
        _employee_Department_Name.Remove(_record_);
        _record_._name = newValue;
        _employee_Department_Name[_record_] = _record_;
    }
    public void SetEmployeeDepartment(IEmployee record, IDepartment newValue) {
        Employee _record_;
        if ( !_employee_pk.TryGetValue(record.Id, out _record_)) {
            throw new ArgumentException(String.Format(
                "'Employee' with id '{0}' does not exist.",
                record.Id));
        }
        if (Object.Equals(_record_._department, newValue)) {
            return;
        }
        _employee_Key._department = (Department)newValue;
        _employee_Key._name = _record_._name;
        if ( _employee_Department_Name.ContainsKey(_employee_Key)) {
            throw new ArgumentException(
              "Fields 'Department Name' are not unique for 'Employee'.");
        }
        Department _that_;
        if (newValue == null ) {
            _that_ = null;
        } else if (!_department_pk.TryGetValue(newValue.Id, out _that_)) {
            throw new ArgumentException(String.Format(
                "'Department' with id '{0}' does not exist.",
                newValue.Id));
        }
        if (_record_._department != null ) {
            _record_._department._refCount--;
        }
        _employee_Department_Name.Remove(_record_);
        _record_._department = _that_;
        _employee_Department_Name[_record_] = _record_;
        if (_record_._department != null ) {
            _record_._department._refCount++;
        }
    }
    public IDepartment InsertDepartment(int id, string title) {
        if ( id == 0 ) {
            id = _next_department;
        } else {
            if (_department_pk.ContainsKey(id)) {
                string className = _department_pk[id].GetType().Name;
                throw new ArgumentException(String.Format(
                    "'{0}' with id '{1}' already exists.",
                    className, id));
            }
        }
        if ( id >= _next_department ) {
            _next_department = id + 1;
        }
        _department_Key._title = title;
        if ( _department_Title.ContainsKey(_department_Key)) {
            throw new ArgumentException(
              "Fields 'Title' are not unique for 'Department'.");
        }
        var _record_ = new Department(id);
        _record_._title = title;
        _department_pk[id] = _record_;
        _department_Title[_record_] = _record_;
        return _record_;
    }
    public IDepartment GetDepartment(int id) {
        Department _record_;
        if (!_department_pk.TryGetValue(id, out _record_)) {
            return null;
        }
        return _record_;
    }
    public int DepartmentCount() {
        return _department_pk.Count;
    }
    public IEnumerable<IDepartment> EachDepartment() {
        foreach (KeyValuePair<int, Department> record in _department_pk) {
            yield return record.Value;
        }
    }
    public void DeleteDepartment(IDepartment record) {
        if (record == null) return;
        Department _record_;
        var deletionList = new System.Collections.Generic.HashSet<IDelRecord>();
        if ( !_department_pk.TryGetValue(record.Id, out _record_)) {
            throw new ArgumentException(String.Format(
                "'Department' with id '{0}' does not exist.",
                record.Id));
        }
        _record_.PreDeleteOuter(deletionList, false);
        foreach (IDelRecord item in deletionList) {
            item.EnsureCanDelete(deletionList);
        }
        foreach (IDelRecord item in deletionList) {
            item.DoDelete(this, deletionList);
        }
    }
    public IDepartment FindDepartmentByTitle(string title) {
        Department _record_;
        _department_Key._title = title;
        if (_department_Title.TryGetValue(_department_Key, out _record_)) {
            return _record_;
        } else {
            return null;
        }
    }
    public void SetDepartmentTitle(IDepartment record, string newValue) {
        Department _record_;
        if ( !_department_pk.TryGetValue(record.Id, out _record_)) {
            throw new ArgumentException(String.Format(
                "'Department' with id '{0}' does not exist.",
                record.Id));
        }
        if (Object.Equals(_record_._title, newValue)) {
            return;
        }
        _department_Key._title = newValue;
        if ( _department_Title.ContainsKey(_department_Key)) {
            throw new ArgumentException(
              "Fields 'Title' are not unique for 'Department'.");
        }
        _department_Title.Remove(_record_);
        _record_._title = newValue;
        _department_Title[_record_] = _record_;
    }
    public ICompany InsertCompany(int id) {
        if ( id == 0 ) {
            id = _next_company;
        } else {
            if (_company_pk.ContainsKey(id)) {
                string className = _company_pk[id].GetType().Name;
                throw new ArgumentException(String.Format(
                    "'{0}' with id '{1}' already exists.",
                    className, id));
            }
        }
        if ( id >= _next_company ) {
            _next_company = id + 1;
        }
        var _record_ = new Company(id);
        _company_pk[id] = _record_;
        return _record_;
    }
    public ICompany GetCompany(int id) {
        Company _record_;
        if (!_company_pk.TryGetValue(id, out _record_)) {
            return null;
        }
        return _record_;
    }
    public int CompanyCount() {
        return _company_pk.Count;
    }
    public IEnumerable<ICompany> EachCompany() {
        foreach (KeyValuePair<int, Company> record in _company_pk) {
            yield return record.Value;
        }
    }
    public void DeleteCompany(ICompany record) {
        if (record == null) return;
        Company _record_;
        var deletionList = new System.Collections.Generic.HashSet<IDelRecord>();
        if ( !_company_pk.TryGetValue(record.Id, out _record_)) {
            throw new ArgumentException(String.Format(
                "'Company' with id '{0}' does not exist.",
                record.Id));
        }
        _record_.PreDeleteOuter(deletionList, false);
        foreach (IDelRecord item in deletionList) {
            item.EnsureCanDelete(deletionList);
        }
        foreach (IDelRecord item in deletionList) {
            item.DoDelete(this, deletionList);
        }
    }
    public void SetCompanyMarketing(ICompany record, IDepartment newValue) {
        Company _record_;
        if ( !_company_pk.TryGetValue(record.Id, out _record_)) {
            throw new ArgumentException(String.Format(
                "'Company' with id '{0}' does not exist.",
                record.Id));
        }
        if (Object.Equals(_record_._marketing, newValue)) {
            return;
        }
        Department _that_;
        if (newValue == null ) {
            _that_ = null;
        } else if (!_department_pk.TryGetValue(newValue.Id, out _that_)) {
            throw new ArgumentException(String.Format(
                "'Department' with id '{0}' does not exist.",
                newValue.Id));
        }
        if (_record_._marketing != null ) {
            _record_._marketing._refCount--;
        }
        _record_._marketing = _that_;
        if (_record_._marketing != null ) {
            _record_._marketing._refCount++;
        }
    }

    public static void Equal(object expected, object actual) {
        // item 209
        if (Object.Equals(expected, actual)) {
            
        } else {
            // item 191
            if (expected is System.Collections.IEnumerable) {
                // item 197
                if (actual is System.Collections.IEnumerable) {
                    // item 200
                    var expectedEn = (System.Collections.IEnumerable)expected;
                    var actualEn = (System.Collections.IEnumerable)actual;
                    // item 211
                    List<object> exList = expectedEn.Cast<object>().ToList();
                    List<object> acList = actualEn.Cast<object>().ToList();
                    // item 201
                    if (exList.Count == acList.Count) {
                        // item 2040001
                        int i = 0;
                        while (true) {
                            // item 2040002
                            if (i < exList.Count) {
                                
                            } else {
                                break;
                            }
                            // item 206
                            Equal(exList[i], acList[i]);
                            // item 2040003
                            i++;
                        }
                    } else {
                        // item 203
                        throw new Exception("Collections have different sizes");
                    }
                } else {
                    // item 199
                    throw new Exception("Both should be IEnumerable");
                }
            } else {
                // item 194
                if (actual is System.Collections.IEnumerable) {
                    // item 195
                    throw new Exception("Both should be IEnumerable");
                } else {
                    // item 207
                    throw new Exception("Objects are not equal.");
                }
            }
        }
    }

    public static void ExpectException(AnyCode code) {
        // item 226
        bool caught = false;
        try {
            code();
        }
        catch {
            caught = true;
        }
        // item 227
        if (caught) {
            
        } else {
            // item 230
            throw new Exception("Exception expected but not thrown.");
        }
    }

    public static void Main() {
        // item 233
        Bar db = new Bar();
        // item 160
        Bar.ICompany yellow = db.InsertCompany(0);
        Bar.ICompany grey = db.InsertCompany(0);
        // item 161
        Bar.IDepartment yellow_m = db.InsertDepartment(0, "Yellow marketing");
        Bar.IDepartment grey_m = db.InsertDepartment(0, "Grey marketing");
        // item 162
        Bar.IEmployee grey_e = db.InsertEmployee(0, "Mark", grey_m);
        Bar.IEmployee grey_e2 = db.InsertEmployee(0, "John", null);
        // item 178
        ExpectException(() => db.InsertEmployee(0, "Mark", grey_m));
        // item 163
        var fake = new FakeDepartment { 
        	Id = 1000, Title = "Fake" 
        };
        ExpectException(() => db.InsertEmployee(0, "Jack", fake));
        // item 164
        db.SetCompanyMarketing(yellow, yellow_m);
        db.SetCompanyMarketing(grey, grey_m);
        // item 165
        db.SetEmployeeDepartment(grey_e2, grey_m);
        // item 169
        Equal(yellow_m, db.GetDepartment(yellow_m.Id));
        // item 166
        ExpectException(() => db.DeleteDepartment(yellow_m));
        // item 167
        db.DeleteCompany(yellow);
        // item 168
        Equal(null, db.GetDepartment(yellow_m.Id));
        Equal(null, db.GetCompany(yellow.Id));
        // item 170
        ExpectException(() => db.DeleteCompany(grey));
        // item 171
        db.SetEmployeeDepartment(grey_e, null);
        // item 172
        db.DeleteEmployee(grey_e2);
        // item 173
        db.DeleteCompany(grey);
        // item 174
        Equal(null, db.GetCompany(grey.Id));
        Equal(null, db.GetDepartment(grey_m.Id));
    }

    public static void NotEqual(object left, object right) {
        // item 217
        if (Object.Equals(left, right)) {
            // item 220
            throw new Exception("Objects are equal.");
        } else {
            
        }
    }
}

