/*
 * The MIT License
 *
 * Copyright 2016 CloudBees, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package hudson.model;

import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.util.Arrays;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import jenkins.model.DirectlyModifiableTopLevelItemGroup;
import net.sf.json.JSONObject;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.MockFolder;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.StaplerRequest;

public class ViewDescriptorTest {

    @Rule
    public JenkinsRule r = new JenkinsRule();

    /** Checks that {@link ViewDescriptor#doAutoCompleteCopyNewItemFrom} honors {@link DirectlyModifiableTopLevelItemGroup#canAdd}. */
    @Test
    public void canAdd() throws Exception {
        MockFolder d1 = r.createFolder("d1");
        d1.createProject(MockFolder.class, "sub");
        d1.createProject(FreeStyleProject.class, "prj");
        MockFolder d2 = r.jenkins.createProject(RestrictiveFolder.class, "d2");
        assertContains(r.jenkins.getDescriptorByType(AllView.DescriptorImpl.class).doAutoCompleteCopyNewItemFrom("../d1/", d2), "../d1/prj");
    }

    @SuppressWarnings("rawtypes") // the usual API mistakes
    public static class RestrictiveFolder extends MockFolder {

        public RestrictiveFolder(ItemGroup parent, String name) {
            super(parent, name);
        }

        @Override
        public boolean canAdd(TopLevelItem item) {
            return item instanceof FreeStyleProject;
        }

        @TestExtension("canAdd") public static class DescriptorImpl extends TopLevelItemDescriptor {

            @Override public TopLevelItem newInstance(ItemGroup parent, String name) {
                return new RestrictiveFolder(parent, name);
            }

        }

    }

    private void assertContains(AutoCompletionCandidates c, String... values) {
        assertEquals(new TreeSet<>(Arrays.asList(values)), new TreeSet<>(c.getValues()));
    }


    @Test
    @Issue("JENKINS-60579")
    public void invisiblePropertiesOnViewShoudBePersisted() throws Exception {

        //GIVEN a listView that have an invisible property
        ListView myListView = new ListView("Rock");
        myListView.setRecurse(true);
        myListView.setIncludeRegex(".*");

        CustomInvisibleProperty invisibleProperty = new CustomInvisibleProperty();
        invisibleProperty.setSomeProperty("You cannot see me.");
        invisibleProperty.setView(myListView);
        myListView.getProperties().add(invisibleProperty);

        r.jenkins.addView(myListView);

        assertEquals(
                "You cannot see me.",
                r.jenkins
                        .getView("Rock")
                        .getProperties()
                        .get(CustomInvisibleProperty.class)
                        .getSomeProperty());

        //WHEN the users goes with "Edit View" on the configure page
        HtmlPage editViewPage = r.createWebClient().getPage(myListView, "configure");

        //THEN the invisible property is not displayed on page
        assertFalse("CustomInvisibleProperty should not be displayed on the View edition page UI.",
                    editViewPage.asNormalizedText().contains("CustomInvisibleProperty"));


        HtmlForm editViewForm = editViewPage.getFormByName("viewConfig");
        editViewForm.getTextAreaByName("description").type("This list view is awesome !");
        r.submit(editViewForm);

        //Check that the description is updated on view
        await().pollInterval(1, TimeUnit.SECONDS)
                .atMost(10, TimeUnit.SECONDS)
                .until(() -> r.createWebClient().getPage(myListView).asNormalizedText(), containsString("This list view is awesome !"));

        //AND THEN after View save, the invisible property is still persisted with the View.
        assertNotNull("The CustomInvisibleProperty should be persisted on the View.",
                      r.jenkins.getView("Rock").getProperties().get(CustomInvisibleProperty.class));
        assertEquals(
                "You cannot see me.",
                r.jenkins
                        .getView("Rock")
                        .getProperties()
                        .get(CustomInvisibleProperty.class)
                        .getSomeProperty());

    }

    private static class CustomInvisibleProperty extends ViewProperty {

        private String someProperty;

        public void setSomeProperty(String someProperty) {
            this.someProperty = someProperty;
        }

        public String getSomeProperty() {
            return this.someProperty;
        }

        CustomInvisibleProperty() {
            this.someProperty = "undefined";
        }

        @Override
        public ViewProperty reconfigure(StaplerRequest req, JSONObject form) {
            return this;
        }

        @TestExtension
        public static final class CustomInvisibleDescriptorImpl extends ViewPropertyDescriptor {

            @Override
            public String getId() {
                return "CustomInvisibleDescriptorImpl";
            }

            @Override
            public boolean isEnabledFor(View view) {
                return true;
            }
        }

        @TestExtension
        public static final class CustomInvisibleDescriptorVisibilityFilterImpl extends DescriptorVisibilityFilter {

            @Override
            public boolean filter(Object context, Descriptor descriptor) {
                return false;
            }
        }
    }

}

@@ -1177,35 +1177,44 @@
 org.
-awaitility.Awaitility.await
+hamcrest.CoreMatchers.containsString
 ;%0Aim
@@ -1242,35 +1242,32 @@
 est.
-Core
 Matcher
-s.containsString
+Assert.assertThat
 ;%0Aim
@@ -1559,46 +1559,8 @@
 et;%0A
-import java.util.concurrent.TimeUnit;%0A
 impo
@@ -4331,24 +4331,84 @@
 figure page%0A
+        JenkinsRule.WebClient client = r.createWebClient();%0A
         Html
@@ -4427,35 +4427,22 @@
 wPage = 
-r.createWebC
+c
 lient
-()
 .getPage
@@ -4852,20 +4852,23 @@
 ption%22).
-type
+setText
 (%22This l
@@ -4994,143 +4994,24 @@
    a
-wait().pollInterval(1, TimeUnit.SECONDS)%0A                .atMost(10, TimeUnit.SECONDS)%0A                .until(() -%3E r.createWebC
+ssertThat(c
 lient
-()
 .get

Use `setText` rather than `type` in `ViewDescriptorTest` (#7289)