001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Anahide Tchertchian
018 */
019package org.nuxeo.functionaltests.forms;
020
021import java.util.ArrayList;
022import java.util.List;
023
024import org.apache.commons.lang3.StringUtils;
025import org.openqa.selenium.By;
026import org.openqa.selenium.WebDriver;
027import org.openqa.selenium.WebElement;
028
029/**
030 * Element representing a select many checkbox directory widget.
031 *
032 * @since 7.4
033 */
034public class SelectManyCheckboxDirectoryWidgetElement extends WidgetElement {
035
036    public SelectManyCheckboxDirectoryWidgetElement(WebDriver driver, String id) {
037        super(driver, id);
038    }
039
040    @Override
041    public void setInput(WebElement elt, String value) {
042        List<WebElement> options = getInputElement().findElements(By.xpath(".//input[@type='checkbox']"));
043        List<String> ids = new ArrayList<String>();
044        if (StringUtils.isBlank(value)) {
045            for (WebElement option : options) {
046                if (option.isSelected()) {
047                    ids.add(option.getAttribute("id"));
048                }
049            }
050        } else {
051            String[] split = value.split(",");
052            for (String v : split) {
053                for (WebElement option : options) {
054                    if (option.getAttribute("value").equals(v) && !option.isSelected()) {
055                        ids.add(option.getAttribute("id"));
056                    }
057                }
058            }
059        }
060        // click options by id in case widget is ajaxified
061        for (String id : ids) {
062            driver.findElement(By.id(id)).click();
063        }
064    }
065
066    @Override
067    public String getInputValue() {
068        StringBuilder res = new StringBuilder();
069        List<WebElement> options = getInputElement().findElements(By.xpath(".//input[type='checkbox']"));
070        for (WebElement option : options) {
071            if (option.isSelected()) {
072                if (res.length() != 0) {
073                    res.append(",");
074                }
075                res.append(option.getAttribute("value"));
076            }
077        }
078        return res.toString();
079    }
080
081}