import $ from "jquery";
import { FunctionFactory } from "survey-jquery";

import { Model, StylesManager } from "survey-jquery";
import "survey-jquery/defaultV2.css";
import "./index.css";
import { json } from "./json"
StylesManager.applyTheme("defaultV2");
function setOfficialCountryName(params) {
    if (params.length < 2)
        return;
    var country = params[0];
    var officialName = params[1];
    var survey = this.survey;
    if (!country || !country.length) {
        survey.clearValue(officialName);
        return;
    }
    survey.setVariable("request_processing", true);
    survey.setVariable("request_error", null);
    country = country
        .charAt(0)
        .toUpperCase() + country
        .slice(1)
        .toLowerCase();
    $.ajax({
        url: "https://surveyjs.io/api/CountriesExample?name=" + country,
        type: "GET",
        success: function (data) {
            if (!!data && data.length > 0) {
                var countryValue = data[0];
                survey.setValue(officialName, countryValue.officialName);
                survey.setVariable("hasError", false);
            } else {
                survey.setVariable("hasError", true);
                survey.setVariable("request_error", "The country is not found.");
                survey.clearValue(officialName);
            }
                survey.setVariable("request_processing", false);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            survey.setVariable("hasError", true);
            survey.setVariable("request_error", "The country is not found.");
            survey.clearValue(officialName);
        }
    });
}
FunctionFactory.Instance.register("setOfficialCountryName", setOfficialCountryName);
const survey = new Model(json);
$("#surveyElement").Survey({ model: survey });
