/**
 * Copyright 2012-2015 Rafal Lewczuk <rafal.lewczuk@jitlogic.com>
 * <p/>
 * This is free software. You can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * <p/>
 * This software is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * <p/>
 * You should have received a copy of the GNU General Public License
 * along with this software. If not, see <http://www.gnu.org/licenses/>.
 */

package com.jitlogic.klikacz.core.phantom;

import com.jitlogic.klikacz.core.SlacRuntimeException;
import com.jitlogic.klikacz.data.phantom.PhantomScenario;
import com.jitlogic.klikacz.data.phantom.PhantomStep;
import org.joox.Match;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import static org.joox.JOOX.*;

public class SeleniumImporter {

    private Pattern RE_DOCTYPE = Pattern.compile("<!DOCTYPE.*>");

    public PhantomScenario importScenario(String xml) {
        try {
            // So many things in Java are such a pieces of shit ....
            // in this case some idiot "conceived" that fetching DTDs every time XML document is parsed
            // is actually a good idea and made disabling this crap almost impossible
            xml = xml.replace("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">", "");
            Match doc = $("doc", xml);
            PhantomScenario rslt = new PhantomScenario();
            rslt.setUrl(doc.find("link").attr("href"));
            rslt.setName(doc.find("table").find("thead").find("tr").find("td").content());


            List<Match> trs = doc.find("table").find("tr").each();

            List<PhantomStep> steps = new ArrayList<>();

            int nstep = 1;
            for (Match tr : trs) {
                if (tr.children().size() == 3) {
                    steps.add(PhantomStep.wcs(
                            nstep,
                            tr.children().get(0).getTextContent(),
                            tr.children().get(1).getTextContent(),
                            tr.children().get(2).getTextContent()
                    ));
                    nstep++;
                }
            }

            rslt.setSteps(steps);

            return rslt;
        } catch (Exception e) {
            throw new SlacRuntimeException("Error reading XML document ", e);
        }
    }

}
