using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class CrossOverController
{
    private const int crossCount = 3;
    
    private delegate bool CrossOverFunction(Home homeA, Home homeB);

    private static List<CrossOverFunction> crossOverFunctions = new List<CrossOverFunction>()
    {
        CrossAddRoom,
        CrossRemoveRoom,
//        CrossLink
    };
    
    public static Home CrossOver(Home homeA, Home homeB)
    {
        var newHome = new Home();
        newHome.SetUp(homeA);
        
        for (int i = 0; i < crossCount; i++)
        {
            Utils.Shuffle(crossOverFunctions);

            foreach (var crossFunction in crossOverFunctions)
            {
                if (crossFunction(newHome, homeB))
                    break;
            }
        }
        
        newHome.CenterHome();

        return newHome;
    }

    private static bool CrossAddRoom(Home homeA, Home homeB)
    {
        if (homeA.rooms.Count >= Home.maxRoomCount)
            return false;
        
        var diff = homeA.GetRoomDiff(homeB);

        Utils.Shuffle(Room.roomTypes);
        
        foreach (var roomType in Room.roomTypes)
        {
            if (diff[roomType] < 0)
            {
                var targetRoom = homeB.GetRoomOfType(roomType);
                var newRoom = new Room(targetRoom);

                homeA.AddRoom(newRoom);
                homeA.PositionRoom(newRoom);

                return true;
            }
        }
        
        return false;
    }
    
    private static bool CrossRemoveRoom(Home homeA, Home homeB)
    {
        var diff = homeA.GetRoomDiff(homeB);

        Utils.Shuffle(Room.roomTypes);
        
        foreach (var roomType in Room.roomTypes)
        {   
            if (homeA.GetRoomTypeCount(roomType) > Home.mustHaveRooms[roomType] && diff[roomType] > 0)
            {
                var targetRoom = homeA.GetRoomOfType(roomType);
                
                homeA.RemoveRoom(targetRoom);

                return true;
            }
        }
        
        return false;
    }
    
    private static bool CrossLink(Home homeA, Home homeB)
    {
        return true;
    }
}