import { BudgetExpenseService } from '../services/budgetExpenseService.js'
import { ProjectSearchService } from '../services/projectSearchService.js'
import { sendError } from '../utils/response.js'
// import { OftenError } from '../utils/oftenError.js'
import { GeneralService } from '../share/generalservice.js';
import { trim_all_array } from '../utils/trim.js'
import { verifyToken, generateToken } from '../utils/token.js'
import { Interface } from '../interfaces/Interface.js';


export class budgetExpense {

    constructor() {
        this.generalService = new GeneralService();
        this.Interface = new Interface();
        this.budgetExpenseService = new BudgetExpenseService();
        this.projectSearchService = new ProjectSearchService();
    }

    async onNavigate(req, res) {
        this.generalService.devhint(1, 'budgetExpense.js', 'onNavigate() start');
        let organization = req.body.organization;
        const prommis = await this.onBudgetExpense(req, res, organization);
        return prommis;
    }

    // TODO:
    async onBudgetExpense(req, res, database) {
        let idx = -1
        let aryResult = []
        let condition = {}
        try {
            let token = req.headers.authorization?.split(' ')[1];
            const decoded = verifyToken(token);
            database = decoded.organization
            var column = ""

            column = `prjseq`
            condition['prjseq'] = req.body.request.prjseq;

            // Check if Project is valid
            aryResult = await this.projectSearchService.getProjectSearch(database, column, condition)
        } catch (error) {
            idx = 1;
        } finally {
            if (idx === 1) return sendError('เกิดข้อผิดพลาดไม่คาดคิดเกิดขึ้น', 'Unexpected error');
            if (!aryResult) return sendError('ไม่พบการมีอยู่ของข้อมูล', 'Cannot Find Any Data');

            if (aryResult.length == 1) {
                // TODO: 

                let prommis = await this.makeArySave(req);
                return prommis
            } else {
                return sendError('ไม่พบการมีอยู่ของข้อมูลโครงการ', 'Cannot Find Project Data');
            }
        }
    }

    async makeArySave(req) {
        let arysave = {
            methods: 'post',
            bdgseq: req.body.request.bdgseq,
            bdgnam: req.body.request.bdgnam,
            bdgcod: req.body.request.bdgcod,
            bdgttl: req.body.request.bdgttl
        }
        return this.Interface.saveInterface('bdgmst', arysave, req);
    }
}