package ru.yandex.wmconsole.verification;

import java.io.IOException;
import java.net.URL;

import org.apache.http.Consts;
import org.cyberneko.html.parsers.SAXParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import ru.yandex.wmconsole.data.VerificationStateEnum;
import ru.yandex.wmconsole.data.info.UsersHostsInfo;
import ru.yandex.wmtools.common.sita.SitaUrlFetchResponse;

/**
 * Old meta-tag verifier based on NekoHTML parser.
 */
public class SaxMetaTagChecker implements MetaTagVerifier.MetaTagChecker {
    private static final Logger log = LoggerFactory.getLogger(SaxMetaTagChecker.class);

    @Override
    public UsersHostsInfo checkMetatag(UsersHostsInfo verInfo, URL urlAddress,
            SitaUrlFetchResponse sitaUrlFetchResponse)
    {
        CheckMetaTagContentHandler checkMetaTagContentHandler = new CheckMetaTagContentHandler(
                "yandex-verification",
                VerificationIdentifier.valueOf(verInfo.getVerificationUin()).toString());

        try {
            SAXParser saxParser = new SAXParser();
            saxParser.setContentHandler(checkMetaTagContentHandler);
            saxParser.parse(new InputSource(sitaUrlFetchResponse.getDocumentContent(Consts.ISO_8859_1)));
        } catch (IOException e) {
            if (!checkMetaTagContentHandler.isFound()) {
                String verifyFaultLog = "SAX. Checking meta-tag: Not verified: IOException while reading file with meta-tag: " + urlAddress + "\n" + e;
                log.debug(verifyFaultLog);
                return UsersHostsInfo.createNotVerifiedNow(verInfo, VerificationStateEnum.META_TAG_IO_EXCEPTION, verifyFaultLog);
            }
        } catch (SAXException e) {
            if (!checkMetaTagContentHandler.isFound()) {
                String verifyFaultLog = "SAX. Checking meta-tag: Not verified: SAXException while reading file with meta-tag: " + urlAddress + "\n" + e;
                log.debug(verifyFaultLog);
                return UsersHostsInfo.createNotVerifiedNow(verInfo, VerificationStateEnum.META_TAG_PARSER_EXCEPTION, verifyFaultLog);
            }
        } catch (Throwable e) {
            if (!checkMetaTagContentHandler.isFound()) {
                String verifyFaultLog = "SAX. Checking meta-tag: Not verified: Throwable thrown while reading file with meta-tag: " + urlAddress + "\n" + e;
                log.debug(verifyFaultLog);
                return UsersHostsInfo.createNotVerifiedNow(verInfo, VerificationStateEnum.META_TAG_PARSER_EXCEPTION, verifyFaultLog);
            }
        }

        if (checkMetaTagContentHandler.isFound()) {
            return UsersHostsInfo.createVerifiedNow(verInfo);
        } else {
            return UsersHostsInfo.createNotVerifiedNow(verInfo, VerificationStateEnum.META_TAG_VERIFICATION_TAG_NOT_FOUND, checkMetaTagContentHandler.getFaultLog());
        }
    }
}
