/*
        public static ConfigNode getKSPIResourcesNuclearFile(string path_WarpPlugin_ResourcesNuclear_cfg)
        {
            string p = Utilities.getCustomPluginSettingsFilePath(path_WarpPlugin_ResourcesNuclear_cfg);
            ConfigNode config = null;
            config = ConfigNode.Load(p);
            //ConfigNode[] Resources = config.GetNodes("RESOURCE_DEFINITION");
            return config;
        }
        public static ConfigNode getORSResourcesAthmosphericFile(string path_OpenResourceSystem_atmosphericresourcedefinitions_cfg)
        {
            string p = Utilities.getCustomPluginSettingsFilePath(path_OpenResourceSystem_atmosphericresourcedefinitions_cfg);
            ConfigNode config = null;
            config = ConfigNode.Load(p);
            //ConfigNode[] Resources = config.GetNodes("ATMOSPHERIC_RESOURCE_DEFINITION");
            return config;
        }
        public static ConfigNode getORSResourcesOceanicFile(string path_OpenResourceSystem_oceanicresourcedefinitions_cfg)
        {
            string p = Utilities.getCustomPluginSettingsFilePath(path_OpenResourceSystem_oceanicresourcedefinitions_cfg);
            ConfigNode config = null;
            config = ConfigNode.Load(p);
            //ConfigNode[] Resources = config.GetNodes("OCEANIC_RESOURCE_DEFINITION");
            return config;
        }
        public static ConfigNode getSquadResourcesResourcesGenericFile(string path_Squad_resourcedefinitions_cfg)
        {
            string p = Utilities.getCustomPluginSettingsFilePath(path_Squad_resourcedefinitions_cfg);
            ConfigNode config = null;
            config = ConfigNode.Load(p);
            //ConfigNode[] Resources = config.GetNodes("RESOURCE_DEFINITION");
            return config;
        }
        public static ConfigNode getKethaneResourcesFile(string path_WarpPlugin_ResourcesNuclear_cfg)
        {
            string p = Utilities.getCustomPluginSettingsFilePath(path_WarpPlugin_ResourcesNuclear_cfg);
            ConfigNode config = null;
            config = ConfigNode.Load(p);
            //ConfigNode[] Resources = config.GetNodes("RESOURCE_DEFINITION");
            return config;
        }
        */
        /*
        internal static bool openPersistenFile()
        {
            ConfigNode config = null;
            string persistentfile = null;
            try
            {
                Debug.Log("ResourceRecovery Utilities.openPersistenFile running");
                persistentfile = KSPUtil.ApplicationRootPath + "saves/" + HighLogic.SaveFolder + "/persistent.sfs";
                config = ConfigNode.Load(persistentfile);
                return config;
            }
            catch (Exception ex)
            {
                Debug.Log("ResourceRecovery Utilities.openPersistenFile failed " + persistentfile);
                Debug.Log(ex);
                return config;
            }
            return false;
        }
            */
        /*
        internal static bool SavePersistenFile(ConfigNode config)
        {
            string persistentfile = null;
            try
            {
                Debug.Log("ResourceRecovery Utilities.SavePersistenFile running");
                persistentfile = KSPUtil.ApplicationRootPath + "saves/" + HighLogic.SaveFolder + "/persistent.sfs";
                config.Save(persistentfile);
                Debug.Log("ResourceRecovery Utilities.SavePersistenFile done");
                return true;
            }
            catch (Exception ex)
            {
                Debug.Log("ResourceRecovery Utilities.SavePersistenFile failed " + persistentfile);
                Debug.Log(ex);
                return false;
            }
            return false;
        }
            //*/
        internal static bool perform_resource_transfer(string buttonID, Part part, PartResource resource, string resourceSelected, ScenarioNodeDatabase Sc)
        {
            Vessel vessel = FlightGlobals.fetch.activeVessel;
            Scenario = new ScenarioNodeDatabase();
            Scenario = Sc;

            // get part resource data
            double part_amount = resource.amount;
            double part_maxamount = resource.maxAmount;
            double part_empty_space = part_maxamount - part_amount;
            double part_percentFull = part_amount / part_maxamount * 100.0;
            double part_1_step_value = part_maxamount / 8;
            Debug.Log("ResourceRecovery perform_resource_transfer: part_1_step_value = " + part_1_step_value);
            Debug.Log("ResourceRecovery perform_resource_transfer: part_amount = " + part_amount);
            Debug.Log("ResourceRecovery perform_resource_transfer: part_maxamount = " + part_maxamount);

            // get scenario resource data
            ConfigNode res = Scenario.get_ResourceNode(resourceSelected);
            double storage_amount = 0;
            string storage_amount_string = res.GetValue("storedamount");
            storage_amount_string = (res.GetValue("supply_mode")!="0") ? storage_amount_string : RRSettingsController.get_KSCStorage_capacity();
            double string_number1 = 0;
            if (Double.TryParse(storage_amount_string, out string_number1))
            { storage_amount = string_number1; } else { storage_amount = 0.00; }

            double storage_maxamount = 0;
            string storage_maxamount_string = res.GetValue("storagecapacity");
            double string_number2 = 0;
            if (Double.TryParse(storage_maxamount_string, out string_number2))
            { storage_maxamount = string_number2; } else { storage_maxamount = 0.00; }

            double percentFull = storage_amount / storage_maxamount * 100.0;
            double storage_percentFull = percentFull;
            Debug.Log("ResourceRecovery perform_resource_transfer: storage_amount = " + storage_amount);

            // get requested action data
            double change_new_value=0;
            double change_new_percentFull=0;
            double change_difference;
            switch (buttonID)
            {
                case "Empty":
                     change_new_value = part_1_step_value * 0;
                    break;
                case "1/8":
                     change_new_value = part_1_step_value * 1;
                    break;
                case "1/4":
                     change_new_value = part_1_step_value * 2;
                    break;
                case "3/8":
                     change_new_value = part_1_step_value * 3;
                    break;
                case "Half":
                     change_new_value = part_1_step_value * 4;
                    break;
                case "5/8":
                     change_new_value = part_1_step_value * 5;
                    break;
                case "3/4":
                     change_new_value = part_1_step_value * 6;
                    break;
                case "7/8":
                     change_new_value = part_1_step_value * 7;
                    break;
                case "Full":
                     change_new_value = part_1_step_value * 8;
                    break;
            }
            change_new_percentFull = change_new_value / part_maxamount * 100.0;
            change_difference = change_new_value - part_amount;
            Debug.Log("ResourceRecovery perform_resource_transfer: change_new_value - part_amount = change_difference : change_difference=" + change_difference);

            // validate actions
            storage_amount = (res.GetValue("supply_mode") != "0") ? storage_amount : change_difference;
            if (storage_amount - change_difference < 0)
            { change_difference = storage_amount; }
            if (storage_amount - change_difference < 0)
            { change_difference = storage_amount; }
            Debug.Log("ResourceRecovery perform_resource_transfer: change_difference = " + change_difference);
            if (part_empty_space - change_difference < 0)
            { change_difference = part_empty_space; }
            Debug.Log("ResourceRecovery perform_resource_transfer: change_difference = " + change_difference);

            // perform actions
            ConfigNode RootNode;
            RootNode = Scenario.get_RootNode();
            Debug.Log("ResourceRecovery perform_resource_transfer: resource.amount = " + resource.amount);
            double new_part_amount = resource.amount + change_difference;
            new_part_amount = (part_maxamount > new_part_amount) ? new_part_amount : part_maxamount;
            new_part_amount = (new_part_amount > 0) ? new_part_amount : 0;
            resource.amount = new_part_amount;
            Debug.Log("ResourceRecovery perform_resource_transfer: resource.amount = " + resource.amount);
            Debug.Log("ResourceRecovery perform_resource_transfer: storage_amount = " + storage_amount);
            double new_storage_amaount = storage_amount - change_difference;
            new_storage_amaount = (new_storage_amaount > 0) ? new_storage_amaount : 0;
            Debug.Log("ResourceRecovery perform_resource_transfer: new_storage_amaount = " + new_storage_amaount);

            if (Scenario.modify_ResourceNode_by_ResourceName(resourceSelected, "storedamount", new_storage_amaount.ToString()))
            {
                GamePersistence.SaveGame("persistent", HighLogic.SaveFolder, SaveMode.OVERWRITE);
                if (Scenario.save())
                {
                    Debug.Log("ResourceRecovery perform_resource_transfer Utilities.SavePluginSaveFile(RootNode) worked");
                    return true;
                }
                else
                {
                    Debug.Log("ResourceRecovery EXCEPTION: perform_resource_transfer SavePluginSaveFile failed");
                    return false;
                }
            }
            Debug.Log("perform_resource_transfer Clicked buttonID=" + buttonID + " part.partInfo.title=" + part.partInfo.title + " resource.resourceName=" + resource.resourceName + " resourceSelected=" + resourceSelected);
            return false;
            //return true;
        }
        internal void RefuelMain(int id, ScenarioNodeDatabase Sc)
        {
            style = RRSettingsController.get_label_default();
            style_10px_row = RRSettingsController.get_label_10px();
            style_20px_row = RRSettingsController.get_label_20px();
            style_40px_row = RRSettingsController.get_label_40px();
            style_60px_row = RRSettingsController.get_label_60px();
            style_80px_row = RRSettingsController.get_label_80px();
            style_100px_row = RRSettingsController.get_label_100px();
            style_120px_row = RRSettingsController.get_label_120px();
            style_stretchWidth_row = RRSettingsController.get_label_stretchWidth();
            get_button_80px = RRSettingsController.get_button_80px();
            buttonStyle = RRSettingsController.get_button_100px();
            buttonStyle_active = RRSettingsController.get_button_100px_active();
            splitter = RRSettingsController.get_splitter();

            vessel = FlightGlobals.fetch.activeVessel;
            Scenario = new ScenarioNodeDatabase();
            Scenario = Sc;
            //RootNode = Scenario.get_RootNode();
            Scenario.update_StorageTotals();

            GUILayout.Label("FlightRefuelController: ToDo", style);
            //string currentPlanet = Utilities.get_current_planet();
            //ConfigNode PlanetNode = Scenario.get_PlanetNode(currentPlanet);
            groupFilter = (groupFilter == null) ? "all" : groupFilter;
            groupFilter = ButtonController.get_groupFilter("all");

            //if (vessel.checkLanded())
            if (IsStationary())
            {
                if (resourceSelected != null)
                {
                    ConfigNode SelectedResource = Scenario.get_ResourceNode(resourceSelected);
                    string res_nam = resourceSelected;
                    //Debug.Log("ResourceRecovery: RefuelMain: beginn resourceSelected");
                    GUILayout.BeginHorizontal();
                    GUILayout.BeginVertical();

                    GUILayout.BeginHorizontal();
                    if (GUILayout.Button("Back", get_button_80px))
                    {
                        Debug.Log("Resource Recovery: resourceSelected: Clicked BackButton");
                        resourceSelected = null;
                    }
                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();

                    GUILayout.BeginVertical();
                    GUILayout.Label("ResourceData: " + res_nam, style, GUILayout.Width(200));
                    if (RRSettingsController.get_KSCPlanet()!=Utilities.get_current_planet())
                    {
                        double string_number3 = 0;
                        double.TryParse(SelectedResource.GetValue("storagecapacity"), out string_number3);
                        GUILayout.Label(String.Format("Storage Capacity: {0}", string_number3), style_120px_row);
                    }
                    else
                    {
                        GUILayout.Label(String.Format("Storage Capacity: {0}", SelectedResource.GetValue("storagecapacity")), style_120px_row);
                    }
                    if(SelectedResource.GetValue("supply_mode") != "0")
                    {
                        double string_number2 = 0;
                        double.TryParse(SelectedResource.GetValue("storedamount"), out string_number2);
                        GUILayout.Label(String.Format("Available: {0}", Math.Round(string_number2,2)), style_120px_row);
                    }
                    else
                    {
                        GUILayout.Label(String.Format("Available: {0}", RRSettingsController.get_resource_supply_mode_definition(0)), style_120px_row);
                    }
                    GUILayout.EndVertical();

                    GUILayout.BeginVertical();
                    GUILayout.Label("ShipData:", style_100px_row);
                    GUILayout.Label(String.Format("{0}", vessel.GetName()), style_120px_row);

                    resources = new Dictionary<string, ResourceInfo>();
                    RebuildPartsLists(vessel, resources);
                    double all_parts_max_amount = 0;
                    double all_parts_amount = 0;
                    double all_parts_required = 0;
                    foreach (KeyValuePair<string, ResourceInfo> pair in GetResourceInfo())
                    {
                        ResourceInfo resourceInfo = pair.Value;
                        resourceInfo.pair_key = pair.Key;
                        resourceInfo.isShowing = (pair.Key != resourceSelected) ? false : true;
                        if (resourceInfo.isShowing)
                        {
                            foreach (ResourcePartMap partInfo in resourceInfo.parts)
                            {
                                PartResource resource = partInfo.resource;
                                all_parts_max_amount += resource.maxAmount;
                                all_parts_amount += resource.amount;
                            }
                        }
                    }
                    all_parts_required =  all_parts_max_amount - all_parts_amount;

                    GUILayout.Label(String.Format("maxAmount: {0}", Math.Round(all_parts_max_amount,2)), style_120px_row);
                    GUILayout.Label(String.Format("Amount: {0}", Math.Round(all_parts_amount,2)), style_120px_row);
                    GUILayout.Label(String.Format("Required: {0}", Math.Round(all_parts_required,2)), style_120px_row);
                    GUILayout.EndVertical();

                    GUILayout.EndHorizontal();

                    GUILayout.EndVertical();
                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal(splitter); GUILayout.EndHorizontal();
                    GUILayout.Label("Parts List:", style_100px_row);
                    ResourceRowHeaderPartsList();
                    GUILayout.BeginHorizontal(splitter); GUILayout.EndHorizontal();
                    scrollPosition = GUILayout.BeginScrollView(scrollPosition);
                    GUILayout.BeginVertical();

                    foreach (KeyValuePair<string, ResourceInfo> pair in GetResourceInfo())
                    {
                        //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 1");
                        ResourceInfo resourceInfo = pair.Value;
                        resourceInfo.pair_key = pair.Key;
                        //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 2");
                        resourceInfo.isShowing = (pair.Key != resourceSelected) ? false : true;
                        //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair pair.Key=" + pair.Key);
                        //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair resourceInfo.isShowing=" + resourceInfo.isShowing);
                        if (resourceInfo.isShowing)
                        {

                            foreach (ResourcePartMap partInfo in resourceInfo.parts)
                            {
                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 4");
                                PartResource resource = partInfo.resource;
                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair resource=" + resource);
                                Part part = partInfo.part;
                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair part=" + part);
                                double percentFull = resource.amount / resource.maxAmount * 100.0;
                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 7");

                                GUILayout.BeginVertical();
                                GUILayout.BeginHorizontal();

                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 8");
                                string partTitle = part.partInfo.title;
                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair partTitle=" + partTitle);
                                GUILayout.Label(partTitle.Substring(0, Math.Min(30, partTitle.Length)), style);
                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 10");
                                GUILayout.FlexibleSpace();
                                GUILayout.Label(resource.maxAmount.ToString("F2"), style_60px_row);
                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 11");
                                GUILayout.Label(resource.amount.ToString("F2"), style_60px_row);
                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 12");
                                GUILayout.Label(percentFull.ToString("F1") + "%", style_60px_row);
                                GUILayout.EndHorizontal();

                                GUILayout.BeginHorizontal();
                                GUILayout.FlexibleSpace();
                                //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 13");
                                List<string> RefuelOptions = RRSettingsController.get_VesselRefuelOptionsList();
                                List<string> ro = new List<string>();
                                int count = 0;
                                foreach (string f in RefuelOptions)
                                {
                                    ro.Add(f);
                                    count++;
                                }
                                ButtonController.GetResourceOptionsButtons(ro, part, resource, resourceSelected, Scenario);
                                GUILayout.EndHorizontal();

                                GUILayout.EndVertical();
                                if (Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
                                {
                                    SetPartHighlight(partInfo.part, Color.green);
                                }
                                else
                                {
                                    ClearHighlight(partInfo.part);
                                }
                                GUILayout.BeginHorizontal(splitter); GUILayout.EndHorizontal();
                            }
                            //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 14");
                        }
                        //Debug.Log("ResourceRecovery: RefuelMain: foreach KeyValuePair 15");
                    }
                    //Debug.Log("ResourceRecovery: RefuelMain: done foreach KeyValuePair");

                    GUILayout.EndVertical();
                    GUILayout.EndScrollView();

                    //Debug.Log("ResourceRecovery: RefuelMain: done resourceSelected");
                }
                else
                {
                    //Debug.Log("ResourceRecovery: RefuelMain: beginn foreach FilterOptions");
                    GUILayout.BeginHorizontal();
                    List<string> FilterOptions = RRSettingsController.get_ResourceGroupList();
                    List<string> fo = new List<string>();
                    int count = 0;
                    foreach (string f in FilterOptions)
                    {
                        string foo = f;
                        if (foo == "none")
                        { foo = "all"; }
                        fo.Add(foo);
                        count++;
                    }
                    ButtonController.GetResourceFilterButtons(fo, groupFilter);
                    GUILayout.EndHorizontal();

                    //Debug.Log("ResourceRecovery: RefuelMain: beginn ResourceRowHeader");
                    GUILayout.BeginHorizontal(splitter); GUILayout.EndHorizontal();
                    ResourceRowHeader();
                    GUILayout.BeginHorizontal(splitter); GUILayout.EndHorizontal();
                    scrollPosition = GUILayout.BeginScrollView(scrollPosition);
                    GUILayout.BeginVertical();

                    //Debug.Log("ResourceRecovery: RefuelMain: beginn Scenario.get_ResourcesNode 1");
                    //Debug.Log("ResourceRecovery: RefuelMain: beginn Scenario.get_ResourcesNode 2  Scenario=" + Scenario + "  Scenario.ToString()=" + Scenario.ToString() + "  Scenario.total_number_recource_tanks=" + Scenario.total_number_recource_tanks);
                    ConfigNode RNode_tmp;
                    //Debug.Log("ResourceRecovery: RefuelMain: beginn Scenario.get_ResourcesNode 3");
                    RNode_tmp = Scenario.get_ResourcesNode();
                    ConfigNode[] RNodes = RNode_tmp.GetNodes("RESOURCE");
                    int counter = 0;
                    //Debug.Log("ResourceRecovery: RefuelMain: beginn RNode_tmp.CountNodes");
                    List<bool> _expanded = new List<bool>();
                    int TotalNumbr = RNode_tmp.CountNodes;

                    //Debug.Log("ResourceRecovery: RefuelMain: beginn foreach RNodes");
                    List<ResourceNodeType> RNodesList = new List<ResourceNodeType>();
                    foreach (ConfigNode node in RNodes)
                    {
                        int string_number = 0;
                        Int32.TryParse(node.GetValue("resourceID"), out string_number);
                        if (node.GetValue("hide") == "0" /*&& node.GetValue("storedamount") != "0.00"*/)
                        {
                            if (groupFilter == "all" || node.GetValue("group") == groupFilter)
                            {
                                RNodesList.Add(new ResourceNodeType()
                                {
                                    name = node.GetValue("name"),
                                    resourceID = string_number,
                                    storagecapacity = node.GetValue("storagecapacity"),
                                    storedamount = node.GetValue("storedamount"),
                                    supply_mode = node.GetValue("supply_mode"),
                                    value_factor = node.GetValue("value_factor"),
                                    display_order = node.GetValue("display_order"),
                                    hide = node.GetValue("hide"),
                                    group = node.GetValue("group")
                                });
                            }
                        }
                    }
                    //Debug.Log("ResourceRecovery: RefuelMain: beginn foreach sortedRNodes");
                    var sortedRNodes = RNodesList.OrderBy(x => x.display_order).ToList();
                    foreach (ResourceNodeType node in sortedRNodes)
                    {
                        _expanded.Add(false);
                        //GUILayout.Label(String.Format("{0}:{1}", node.GetValue("name"), node.GetValue("storedamount")));
                        ResourceRow(node, _expanded, counter, TotalNumbr);
                        counter++;
                    }
                    //Debug.Log("ResourceRecovery: RefuelMain: end foreach");
                    GUILayout.EndVertical();
                    GUILayout.EndScrollView();
                }
            }
            else
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Please land the Ship!", style_stretchWidth_row);
                GUILayout.EndHorizontal();

            }
        }