package kaysaar.uaf.scripts;

import com.fs.starfarer.api.EveryFrameScript;
import com.fs.starfarer.api.Global;
import com.fs.starfarer.api.campaign.CoreUITabId;
import com.fs.starfarer.api.characters.MutableCharacterStatsAPI;
import com.fs.starfarer.api.characters.PersonAPI;
import com.fs.starfarer.api.impl.campaign.ids.Skills;
import com.fs.starfarer.api.ui.*;
import com.fs.starfarer.loading.SkillSpec;

import java.util.*;

public class UAFReplaceAISkills implements EveryFrameScript {
    //Inspired with Officer Extension
    boolean inserted = false;
    PersonAPI currentlyAffectedPerson = null;
    public static ArrayList<String> skills = new ArrayList<>();
    UIPanelAPI innerPanel = null;
    DarkHighlightPlugin plugin = null;
    ArrayList<SkillSpec>specs = new ArrayList<>();


    static {
        skills.add(Skills.HELMSMANSHIP);
        skills.add(Skills.DAMAGE_CONTROL);
        skills.add("uaf_aceAggressor");
        skills.add("uaf_silverfoxWit");
        skills.add("uaf_queensSongstress");

    }
    static float w = 70;
    static float h = 70;
    @Override
    public boolean isDone() {
        return false;
    }

    @Override
    public boolean runWhilePaused() {
        return true;
    }

    LinkedHashMap<String, ButtonAPI> skillmap = new LinkedHashMap<>();

    @Override
    public void advance(float amount) {
        if (CoreUITabId.FLEET.equals(Global.getSector().getCampaignUI().getCurrentCoreTab()) || CoreUITabId.REFIT.equals(Global.getSector().getCampaignUI().getCurrentCoreTab())) {
            Object dialog = findSkillDialog();
            if (dialog == null) {
                inserted = false;
                clearData();
                return;
            }
            if (ReflectionUtilis.findArrayOfSkills(dialog) != null) {
                PersonAPI person = (PersonAPI) ReflectionUtilis.findArrayOfSkills(dialog);
                if (person.getAICoreId() != null && person.getAICoreId().contains("neuko")) {
                    if(currentlyAffectedPerson==null){
                        currentlyAffectedPerson = person;
                    }

                    for (MutableCharacterStatsAPI.SkillLevelAPI skillLevelAPI : person.getStats().getSkillsCopy()) {
                        if (skillLevelAPI.getLevel() != 0) {
                            skillLevelAPI.setLevel(1000);
                        }
                    }
                    innerPanel = (UIPanelAPI) ReflectionUtilis.invokeMethod("getInnerPanel", dialog);
                    if (innerPanel == null)
                        return;
                    if (!inserted) {
                        for (UIComponentAPI componentAPI : ReflectionUtilis.getChildrenCopy(innerPanel)) {
                            if (componentAPI instanceof LabelAPI) {
                                if (((LabelAPI) componentAPI).getText().contains("Select")) continue;
                            }
                            if (componentAPI instanceof ButtonAPI) {
                                if (((ButtonAPI) componentAPI).getText() == null) {
                                    w = componentAPI.getPosition().getWidth();
                                    h = componentAPI.getPosition().getHeight();
                                    innerPanel.removeComponent(componentAPI);
                                }
                            } else {
                                innerPanel.removeComponent(componentAPI);
                            }
                        }
                        for (String skill : skills) {
                            populateSkillMap(skill, person);

                        }
                    }

                    if (!inserted) {
                        float x = 10;
                        float y = 40;
                        for (Map.Entry<String, ButtonAPI> componentAPI : skillmap.entrySet()) {
                            x = placeButton(componentAPI, w, h, person, x, y);
                        }
                        plugin = new DarkHighlightPlugin(skillmap, 0.6f,currentlyAffectedPerson);
                        CustomPanelAPI panel = Global.getSettings().createCustom(100, 100, plugin);
                        plugin.setPanelTied(panel);
                        innerPanel.addComponent(panel).inTL(x, y);
                        inserted = true;


                    }
                    handleButtons();
                } else {
                    clearData();
                }

            } else {
                clearData();
            }


        }
    }

    private float placeButton(Map.Entry<String, ButtonAPI> componentAPI, float w, float h, PersonAPI person, float x, float y) {
        componentAPI.getValue().getPosition().setSize(w, h);

        innerPanel.addComponent(componentAPI.getValue()).inTL(x, y);
        innerPanel.bringComponentToTop(componentAPI.getValue());

        x += w + 10;
        return x;
    }

    private void populateSkillMap(String skill, PersonAPI person) {
        CustomPanelAPI panelAPI = Global.getSettings().createCustom(100, 100, null);
        TooltipMakerAPI tooltip = panelAPI.createUIElement(500, 70, false);
        PersonAPI dummy = Global.getFactory().createPerson();
        float level = person.getStats().getSkillLevel(skill);
        boolean demoting = true;

        if (level == 0) {
            level = 1;
            demoting = false;
        }
        dummy.getStats().setSkillLevel(skill, level);
        if (dummy.getStats().hasSkill(skill)) {
            UIComponentAPI component = tooltip.addSkillPanel(dummy, 0f);
            UIComponentAPI tooltipComp = (UIComponentAPI) ReflectionUtilis.getChildrenCopy((UIPanelAPI) component).get(0);
            UIComponentAPI rootTooltipComp = (UIComponentAPI) ReflectionUtilis.getChildrenCopy((UIPanelAPI) tooltipComp).get(0);
            ArrayList<UIComponentAPI> exactSkillButtonsOfCharacter = new ArrayList<>();
            for (UIComponentAPI deepRoot : ReflectionUtilis.getChildrenCopy((UIPanelAPI) rootTooltipComp)) {
                for (UIComponentAPI componentAPI : ReflectionUtilis.getChildrenCopy((UIPanelAPI) deepRoot)) {
                    if(demoting){
                        ((ButtonAPI) ReflectionUtilis.getChildrenCopy((UIPanelAPI) componentAPI).get(0)).setButtonPressedSound("ui_char_decrease_skill");

                    }
                    else{
                        ((ButtonAPI) ReflectionUtilis.getChildrenCopy((UIPanelAPI) componentAPI).get(0)).setButtonPressedSound("ui_char_reset");
                    }
                    ((ButtonAPI) ReflectionUtilis.getChildrenCopy((UIPanelAPI) componentAPI).get(0)).setButtonDisabledPressedSound("ui_char_can_not_increase_skill_or_aptitude");
                    skillmap.put(skill, (ButtonAPI) ReflectionUtilis.getChildrenCopy((UIPanelAPI) componentAPI).get(0));
                }
            }
        }
    }

    public void clearData() {
        skillmap.clear();
        currentlyAffectedPerson = null;
        innerPanel=null;
        plugin = null;
    }

    public Object findSkillDialog() {
        UIPanelAPI panelAPI = ProducitonUtili.getCoreUI();
        if (panelAPI == null) return null;

        for (UIComponentAPI componentAPI : ReflectionUtilis.getChildrenCopy(panelAPI)) {
            if (ReflectionUtilis.hasMethodOfName("getNumSkills", componentAPI)) {
                return componentAPI;
            }
        }
        return null;

    }

    public void handleButtons() {
        for (Map.Entry<String, ButtonAPI> entry : skillmap.entrySet()) {
            if(entry.getValue().isChecked()){
                entry.getValue().setChecked(false);
                float lev =  currentlyAffectedPerson.getStats().getSkillLevel(entry.getKey());
                if(lev==0){
                    currentlyAffectedPerson.getStats().setSkillLevel(entry.getKey(), 20);
                }
                else {

                    currentlyAffectedPerson.getStats().setSkillLevel(entry.getKey(), 0);
                    currentlyAffectedPerson.getStats().decreaseSkill(entry.getKey());
                }
                float x = entry.getValue().getPosition().getX()-innerPanel.getPosition().getX();
                float y = entry.getValue().getPosition().getY()-innerPanel.getPosition().getY()-innerPanel.getPosition().getHeight();
                innerPanel.removeComponent(entry.getValue());
                populateSkillMap(entry.getKey(), currentlyAffectedPerson);
                placeButton(entry, w, h, currentlyAffectedPerson, x, y);
                y = entry.getValue().getPosition().getY()-innerPanel.getPosition().getY()-innerPanel.getPosition().getHeight();
                innerPanel.removeComponent(entry.getValue());
                placeButton(entry, w, h, currentlyAffectedPerson, x, y);
                innerPanel.bringComponentToTop( plugin.getPanelTied());
                break;
            }
        }
    }

}
