/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

====================================================================== */

package org.bodington.util.html;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.List;

import org.bodington.util.Scanner;
import org.bodington.util.ScannerResults;
import org.htmlparser.Parser;
import org.htmlparser.util.ParserException;

public class HtmlScanner implements Scanner
{

    public ScannerResults scan(File source)
    {
        HtmlScannerResults results = new HtmlScannerResults();
        
        try
        {
            Parser parser = HtmlFilterFactory.getParser(source.toURL()
                .openConnection());
            results.messages = HtmlFilterFactory.filter(parser,
                HtmlFilterFactory.PAGE).getMessages();
            results.ok = results.messages.size() == 0;
        }
        catch (ParserException e)
        {
            results.setError("Error parsing HTML: "+ e.getMessage());
        }
        catch (MalformedURLException e)
        {
            results.setError("Internal Error: Failed to load file");
        }
        catch (IOException e)
        {
            results.setError("Internal Error: Failed to read file");
        }
        return results;
    }
    
    private class HtmlScannerResults implements ScannerResults
    {
        private boolean ok = false;
        private List messages;

        public boolean isOk()
        {
            return ok;
            }

        public List getMessages()
        {
            return messages;
        }
        
        private void setError(String error)
        {
            messages = Arrays.asList(new String[]{error});
        }
        
    }

}
