const importcontroller = require('./importcontroller');
const uuid = require('uuid/v4');

class DataIOController {
    async getInitialData() {
        try {
            const initData = await importcontroller.tree_name.findAll();
            return initData;
        } catch (error) {
            throw {
                message: "could not fetch initial data."
            }
        }
    }

    async saveTreeData(params) {
        try {
            if (params.length) {
                for (const survey of params) {
                    survey.id = uuid();
                    const createdSurvey = await importcontroller.input_form.create(survey);

                    if (survey.boundary) {
                        const boundaryData = survey.boundary.map(b => ({ ...b, boundary_id: uuid(), society_id: createdSurvey.id }));
                        await importcontroller.boundary.bulkCreate(boundaryData);
                    }
                    if (survey.trees) {
                        const trees = survey.trees.map(t => ({ ...t, pid: uuid(), society_id: createdSurvey.id }));
                        await importcontroller.info.bulkCreate(trees);
                    }
                }
                return {
                    message: "Data saved"
                }
            }
            throw {
                message: "No data available"
            }
        } catch (error) {
            throw {
                message: "Something went wrong!"
            }
        }
    }
}

module.exports = new DataIOController();