001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Anahide Tchertchian
016 */
017package org.nuxeo.functionaltests.forms;
018
019import java.util.ArrayList;
020import java.util.List;
021
022import org.apache.commons.lang.StringUtils;
023import org.openqa.selenium.By;
024import org.openqa.selenium.WebDriver;
025import org.openqa.selenium.WebElement;
026
027/**
028 * Element representing a select many checkbox directory widget.
029 *
030 * @since 7.4
031 */
032public class SelectManyCheckboxDirectoryWidgetElement extends WidgetElement {
033
034    public SelectManyCheckboxDirectoryWidgetElement(WebDriver driver, String id) {
035        super(driver, id);
036    }
037
038    @Override
039    public void setInput(WebElement elt, String value) {
040        List<WebElement> options = getInputElement().findElements(By.xpath(".//input[@type='checkbox']"));
041        List<String> ids = new ArrayList<String>();
042        if (StringUtils.isBlank(value)) {
043            for (WebElement option : options) {
044                if (option.isSelected()) {
045                    ids.add(option.getAttribute("id"));
046                }
047            }
048        } else {
049            String[] split = value.split(",");
050            for (String v : split) {
051                for (WebElement option : options) {
052                    if (option.getAttribute("value").equals(v) && !option.isSelected()) {
053                        ids.add(option.getAttribute("id"));
054                    }
055                }
056            }
057        }
058        // click options by id in case widget is ajaxified
059        for (String id : ids) {
060            driver.findElement(By.id(id)).click();
061        }
062    }
063
064    @Override
065    public String getInputValue() {
066        StringBuilder res = new StringBuilder();
067        List<WebElement> options = getInputElement().findElements(By.xpath(".//input[type='checkbox']"));
068        for (WebElement option : options) {
069            if (option.isSelected()) {
070                if (res.length() != 0) {
071                    res.append(",");
072                }
073                res.append(option.getAttribute("value"));
074            }
075        }
076        return res.toString();
077    }
078
079}