/**
 * Sort and moving question/section
 */
class SortApi {
    constructor() {
        const survey_id = $('input[name=survey_id]').val();
        const baseUrl = location.origin + '/polls-surveys/survey/'+ survey_id +'/edit/section/';

        this.updateQuestionUrl = baseUrl + 'question/order';
        this.updateSectionUrl = baseUrl + 'order';
        this.moveQuestionToSection = baseUrl + 'move';
    }

    update(questionIdArray, isQuestionUpdate = true) {
        $.ajax({
            method: 'POST',
            url: isQuestionUpdate === true ? this.updateQuestionUrl : this.updateSectionUrl,
            data: {
                csrf_token: $('input[name=csrf_token]').val(),
                order: JSON.stringify(Object.assign({}, questionIdArray.map(item => item)))
            },
            dataType: 'JSON'
        }).fail(function(res) {
            cla.showMessage(lmsg('quiz.survey.question.order.error'));
            console.error(res);
        })
    }

    move(section_id, array_with_questions_id) {
        $.ajax({
            method: 'POST',
            url: this.moveQuestionToSection,
            data: {
                csrf_token: $('input[name=csrf_token]').val(),
                section_id: section_id,
                items: JSON.stringify(Object.assign({}, array_with_questions_id.map(item => item))) // or {...array_with_questions_id}
            },
            dataType: 'JSON'
        }).fail(function(res) {
            cla.showMessage(lmsg('quiz.survey.question.order.error'), null, true)
            console.error(res)
        }).done(res => true)
    }

    modifyUrls(ui_item, section_id) {
        let editLink = ui_item.find('a[name="question_edit"]').attr('href')
        let deleteLink = ui_item.find('a[name="question_delete"]').attr('href')

        // modify url for new section
        const regex = /(?:\/section\/)([0-9]+)/
        editLink = editLink.replace(regex, '/section/' + section_id)
        deleteLink = deleteLink.replace(regex, '/section/' + section_id)

        ui_item.find('a[name="question_edit"]').attr('href', editLink)
        ui_item.find('a[name="question_delete"]').attr('href', deleteLink)
    }
}

export default SortApi;
